From 92d2a2545ffde70851d4727b3d1a3545004be79b Mon Sep 17 00:00:00 2001 From: Mohamed Hegazy Date: Sat, 20 Jan 2018 11:28:23 -0800 Subject: [PATCH] Update LKG --- lib/cs/diagnosticMessages.generated.json | 15 +- lib/de/diagnosticMessages.generated.json | 13 + lib/enu/diagnosticMessages.generated.json.lcg | 22 +- lib/es/diagnosticMessages.generated.json | 15 +- lib/fr/diagnosticMessages.generated.json | 15 +- lib/it/diagnosticMessages.generated.json | 15 +- lib/ja/diagnosticMessages.generated.json | 15 +- lib/ko/diagnosticMessages.generated.json | 15 +- lib/lib.es2017.object.d.ts | 4 +- lib/pl/diagnosticMessages.generated.json | 15 +- lib/protocol.d.ts | 29 +- lib/pt-BR/diagnosticMessages.generated.json | 15 +- lib/ru/diagnosticMessages.generated.json | 15 +- lib/tr/diagnosticMessages.generated.json | 15 +- lib/tsc.js | 4821 ++++++----- lib/tsserver.js | 5295 ++++++------ lib/tsserverlibrary.d.ts | 342 +- lib/tsserverlibrary.js | 5769 +++++++------ lib/typescript.d.ts | 534 +- lib/typescript.js | 7149 +++++++++++------ lib/typescriptServices.d.ts | 534 +- lib/typescriptServices.js | 7149 +++++++++++------ lib/typingsInstaller.js | 400 +- lib/zh-CN/diagnosticMessages.generated.json | 15 +- lib/zh-TW/diagnosticMessages.generated.json | 15 +- 25 files changed, 19304 insertions(+), 12937 deletions(-) diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index f1d38df3225..1ce1f3ab21e 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklarace oboru názvů nemůže být v jiném souboru než třída nebo funkce, se kterou se slučuje.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklarace oboru názvů nemůže být umístěná před třídou nebo funkcí, se kterou se slučuje.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklarace oboru názvů je povolená jenom v oboru názvů nebo v modulu.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Import stylu oboru názvů není možné vyvolat nebo konstruovat a způsobí selhání za běhu.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Inicializátor parametru je povolený jenom v implementaci funkce nebo konstruktoru.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Vlastnost parametru se nedá deklarovat pomocí parametru rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Vlastnost parametru je povolená jenom v implementaci konstruktoru.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Přístupové objekty jsou dostupné, jenom když je cílem ECMAScript 5 a vyšší verze.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Přistupující objekty musí být abstraktní nebo neabstraktní.", "Add_0_to_existing_import_declaration_from_1_90015": "Přidat {0} k existující deklaraci importu z {1}", + "Add_async_modifier_to_containing_function_90029": "Přidat modifikátor async do obsahující funkce", "Add_index_signature_for_property_0_90017": "Přidat signaturu indexu pro vlastnost {0}", "Add_missing_super_call_90001": "Přidat chybějící volání metody super()", "Add_this_to_unresolved_variable_90008": "Přidat k nerozpoznané proměnné this.", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "V parametru signatury indexu nemůže být modifikátor přístupnosti.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "V parametru signatury indexu nemůže být inicializátor.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "V parametru signatury indexu nemůže být anotace typu.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Typ parametru signatury indexu nemůže být alias typu. Místo toho zvažte toto zadání: [{0}: {1}]: {2}.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Typ parametru signatury indexu nemůže být typ sjednocení. Místo toho zvažte použití namapovaného typu objektu.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Parametr signatury indexu musí být typu string nebo number.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Rozhraní může rozšířit jenom identifikátor nebo kvalifikovaný název s volitelnými argumenty typu.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Rozhraní může rozšiřovat jenom třídu nebo jiné rozhraní.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Soubory deklarací typů nejde importovat. Zvažte možnost místo {1} naimportovat {0}.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Proměnnou {0} s vnějším oborem nejde inicializovat ve stejném oboru jako deklaraci {1} s oborem bloku.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Nejde vyvolat výraz, v jehož typu chybí signatura volání. Typ {0} nemá žádné kompatibilní signatury volání.", + "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_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}.", @@ -246,6 +253,7 @@ "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_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_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ý.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Nenašel se soubor deklarací pro modul {0}. {1} má implicitně typ any.", @@ -310,6 +318,7 @@ "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.", "Enable_tracing_of_the_name_resolution_process_6085": "Povolte trasování procesu překladu IP adres.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Povolí interoperabilitu generování mezi moduly CommonJS a ES prostřednictvím vytváření objektů oboru názvů pro všechny importy. Implikuje allowSyntheticDefaultImports.", "Enables_experimental_support_for_ES7_async_functions_6068": "Zapíná experimentální podporu asynchronních funkcí ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Povolí experimentální podporu pro dekorátory ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Povolí experimentální podporu pro generování metadat typu pro dekorátory.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "Nejdelší odpovídající předpona pro {0} je {1}.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Hledání ve složce node_modules, počáteční umístění {0}", "Make_super_call_the_first_statement_in_the_constructor_90002": "Nastavit volání metody super() jako první příkaz v konstruktoru", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Typu mapovaného objektu má implicitně typ šablony any.", "Member_0_implicitly_has_an_1_type_7008": "Člen {0} má implicitně typ {1}.", "Merge_conflict_marker_encountered_1185": "Zjistila se značka konfliktu sloučení.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Spojená deklarace {0} nemůže obsahovat výchozí deklaraci exportu. Zvažte namísto toho možnost přidat samostatnou deklaraci export default {0}.", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Vlastnost {0} nemá žádný inicializátor a není jednoznačně přiřazena v konstruktoru.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt get nemá anotaci návratového typu.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Vlastnost {0} má implicitně typ any, protože její přistupující objekt set nemá anotaci parametrového typu.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Vlastnost {0} v typu {1} nejde přiřadit ke stejné vlastnosti v základním typu {2}.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Vlastnost {0} v typu {1} nejde přiřadit typu {2}.", "Property_0_is_declared_but_its_value_is_never_read_6138": "Deklaruje se vlastnost {0}, ale její hodnota se vůbec nečte.", "Property_0_is_incompatible_with_index_signature_2530": "Vlastnost {0} není kompatibilní se signaturou indexu.", @@ -637,6 +648,7 @@ "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", "Remove_declaration_for_Colon_0_90004": "Odebrat deklaraci pro {0}", + "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.", "Report_errors_in_js_files_8019": "Ohlásit chyby v souborech .js", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "Neukončený literál šablony", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Volání netypové funkce nemusí přijmout argumenty typu.", "Unused_label_7028": "Nepoužívaný popisek", + "Use_synthetic_default_member_95016": "Použije syntetického výchozího člena.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Použití řetězce v příkazu for...of se podporuje jenom v ECMAScript 5 nebo vyšší verzi.", "VERSION_6036": "VERZE", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Hodnota typu {0} nemá žádné vlastnosti společné s typem {1}. Chtěli jste ji volat?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Deklarace const se musejí inicializovat.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Inicializátor člena výčtu const se vyhodnotil na nekonečnou hodnotu.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Inicializátor člena výčtu const se vyhodnotil na nepovolenou hodnotu NaN.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Výčty const se dají použít jenom ve výrazech přístupu k vlastnosti nebo indexu nebo na pravé straně deklarace importu nebo přiřazení exportu.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Výčty const se dají použít jenom ve výrazech přístupu k vlastnosti nebo indexu nebo na pravé straně deklarace importu, přiřazení exportu nebo dotazu na typ.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Příkaz delete nejde volat u identifikátoru ve striktním režimu.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Deklarace výčtu se dají použít jenom v souboru .ts.", "export_can_only_be_used_in_a_ts_file_8003": "Možnost export= se dá použít jenom v souboru .ts.", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index 615d38b1d72..18dbf7c9f22 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Eine Namespacedeklaration darf sich nicht in einer anderen Datei als die Klasse oder Funktion befinden, mit der sie zusammengeführt wird.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Eine Namespacedeklaration darf nicht vor der Klasse oder Funktion positioniert werden, mit der sie zusammengeführt wird.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Eine Namespacedeklaration ist nur in einem Namespace oder Modul zulässig.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Ein Import im Namespacestil kann nicht aufgerufen oder erstellt werden und verursacht zur Laufzeit einen Fehler.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Ein Parameterinitialisierer ist nur in einer Funktions- oder Konstruktorimplementierung zulässig.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Eine Parametereigenschaft darf nicht mithilfe eines rest-Parameters deklariert werden.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Eine Parametereigenschaft ist nur in einer Konstruktorimplementierung zulässig.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Zugriffsmethoden sind nur verfügbar, wenn das Ziel ECMAScript 5 oder höher ist.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Beide Accessoren müssen abstrakt oder nicht abstrakt sein.", "Add_0_to_existing_import_declaration_from_1_90015": "\"{0}\" der vorhandenen Importdeklaration aus \"{1}\" hinzufügen", + "Add_async_modifier_to_containing_function_90029": "Async-Modifizierer zur enthaltenden Funktion hinzufügen", "Add_index_signature_for_property_0_90017": "Indexsignatur für die Eigenschaft \"{0}\" hinzufügen", "Add_missing_super_call_90001": "Fehlenden super()-Aufruf hinzufügen", "Add_this_to_unresolved_variable_90008": "Der nicht aufgelösten Variablen \"this.\" hinzufügen", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Ein Indexsignaturparameter darf keinen Zugriffsmodifizierer besitzen.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Ein Indexsignaturparameter darf keinen Initialisierer besitzen.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Ein Indexsignaturparameter muss eine Typanmerkung besitzen.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Ein Indexsignaturparametertyp darf kein Typalias sein. Erwägen Sie stattdessen die Schreibung \"[{0}: {1}]: {2}\".", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Ein Indexsignaturparametertyp darf kein Union-Typ sein. Erwägen Sie stattdessen die Verwendung eines zugeordneten Objekttyps.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Ein Indexsignaturparameter-Typ muss \"string\" oder \"number\" sein.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Eine Schnittstelle kann nur einen Bezeichner/\"qualified-name\" mit optionalen Typargumenten erweitern.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Eine Schnittstelle kann nur eine Klasse oder eine andere Schnittstelle erweitern.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Typdeklarationsdateien können nicht importiert werden. Importieren Sie ggf. \"{0}\" anstelle von \"{1}\".", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Die Variable \"{0}\" mit dem äußeren Bereich im gleichen Bereich wie die Deklaration \"{1}\" mit dem Blockbereich kann nicht initialisiert werden.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Ein Ausdruck, dessen Typ eine Aufrufsignatur fehlt, kann nicht aufgerufen werden. Der Typ \"{0}\" weist keine kompatiblen Aufrufsignaturen auf.", + "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_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.", @@ -246,6 +253,7 @@ "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_function_0_to_class_95002": "Funktion \"{0}\" in Klasse konvertieren", "Convert_function_to_an_ES2015_class_95001": "Funktion in eine ES2015-Klasse 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.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Es wurde keine Deklarationsdatei für das Modul \"{0}\" gefunden. \"{1}\" weist implizit den Typ \"any\" auf.", @@ -310,6 +318,7 @@ "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.", "Enable_tracing_of_the_name_resolution_process_6085": "Ablaufverfolgung des Namensauflösungsvorgangs aktivieren.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Ermöglicht Ausgabeinteroperabilität zwischen CommonJS- und ES-Modulen durch die Erstellung von Namespaceobjekten für alle Importe. Impliziert \"AllowSyntheticDefaultImports\".", "Enables_experimental_support_for_ES7_async_functions_6068": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Funktionen.", "Enables_experimental_support_for_ES7_decorators_6065": "Ermöglicht experimentelle Unterstützung für asynchrone ES7-Decorators.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Ermöglicht experimentelle Unterstützung zum Ausgeben von Typmetadaten für Decorators.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "Das längste übereinstimmende Präfix für \"{0}\" ist \"{1}\".", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Die Suche erfolgt im Ordner \"node_modules\". Anfangsspeicherort \"{0}\".", "Make_super_call_the_first_statement_in_the_constructor_90002": "super()-Aufruf als erste Anweisung im Konstruktor festlegen", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Der zugeordnete Objekttyp weist implizit einen any-Vorlagentyp auf.", "Member_0_implicitly_has_an_1_type_7008": "Der Member \"{0}\" weist implizit den Typ \"{1}\" auf.", "Merge_conflict_marker_encountered_1185": "Mergekonfliktmarkierung", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Die gemergte Deklaration \"{0}\" darf keine Exportstandarddeklaration enthalten. Fügen Sie ggf. eine separate Deklaration \"export default {0}\" hinzu.", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Die Eigenschaft \"{0}\" weist keinen Initialisierer auf und ist im Konstruktor nicht definitiv zugewiesen.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem get-Accessor eine Parametertypanmerkung fehlt.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Die Eigenschaft \"{0}\" weist implizit den Typ \"any\" auf, weil ihrem set-Accessor eine Parametertypanmerkung fehlt.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann nicht der gleichen Eigenschaft in Basistyp \"{2}\" zugewiesen werden.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Die Eigenschaft \"{0}\" im Typ \"{1}\" kann dem Typ \"{2}\" nicht zugewiesen werden.", "Property_0_is_declared_but_its_value_is_never_read_6138": "Die Eigenschaft \"{0}\" ist deklariert, aber ihr Wert wird nie gelesen.", "Property_0_is_incompatible_with_index_signature_2530": "Die Eigenschaft \"{0}\" ist nicht mit der Indexsignatur kompatibel.", @@ -637,6 +648,7 @@ "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.", "Remove_declaration_for_Colon_0_90004": "Deklaration entfernen für: {0}", + "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.", "Report_errors_in_js_files_8019": "Fehler in .js-Dateien melden.", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "Nicht abgeschlossenes Vorlagenliteral.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Nicht typisierte Funktionsaufrufe dürfen keine Typargumente annehmen.", "Unused_label_7028": "Nicht verwendete Bezeichnung.", + "Use_synthetic_default_member_95016": "Verwenden Sie den synthetischen Member \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Das Verwenden einer Zeichenfolge in einer for...of-Anweisung wird nur in ECMAScript 5 oder höher unterstützt.", "VERSION_6036": "VERSION", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Der Wert des Typs \"{0}\" verfügt über keine gemeinsamen Eigenschaften mit dem Typ \"{1}\". Wollten Sie ihn aufrufen?", diff --git a/lib/enu/diagnosticMessages.generated.json.lcg b/lib/enu/diagnosticMessages.generated.json.lcg index 7cfcb413307..65e40e37f95 100644 --- a/lib/enu/diagnosticMessages.generated.json.lcg +++ b/lib/enu/diagnosticMessages.generated.json.lcg @@ -369,6 +369,12 @@ + + + + + + @@ -2187,12 +2193,6 @@ - - - - - - @@ -2313,6 +2313,12 @@ + + + + + + @@ -4269,9 +4275,9 @@ - + - + diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 351960fc67d..3ac8faf7afd 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una declaración de espacio de nombres no puede estar en un archivo distinto de una clase o función con la que se combina.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una declaración de espacio de nombres no se puede situar antes que una clase o función con la que se combina.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una declaración de espacio de nombres solo se permite en un espacio de nombres o en un módulo.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "No se puede llamar o construir una importación de estilo de espacio de nombres, y provocará un error en tiempo de ejecución.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inicializador de parámetros solo se permite en una implementación de función o de constructor.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Una propiedad de parámetro no se puede declarar mediante un parámetro rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una propiedad de parámetro solo se permite en una implementación de constructor.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Los descriptores de acceso solo están disponibles cuando el destino es ECMAScript 5 y versiones posteriores.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Los descriptores de acceso deben ser los dos abstractos o los dos no abstractos.", "Add_0_to_existing_import_declaration_from_1_90015": "Agregar \"{0}\" a una declaración de importación existente desde \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Agregar el modificador async a la función contenedora", "Add_index_signature_for_property_0_90017": "Agregar una signatura de índice para la propiedad \"{0}\"", "Add_missing_super_call_90001": "Agregar la llamada a \"super()\" que falta", "Add_this_to_unresolved_variable_90008": "Agregar \"this.\" a una variable no resuelta", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parámetro de signatura de índice no puede tener un modificador de accesibilidad.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parámetro de signatura de índice no puede tener un inicializador.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parámetro de signatura de índice debe tener una anotación de tipo.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Un tipo de parámetro de firma de índice no puede ser un alias de tipo. Considere la posibilidad de escribir en su lugar \"[{0}: {1}]: {2}\".", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Un tipo de parámetro de firma de índice no puede ser un tipo de unión. Considere la posibilidad de usar en su lugar un tipo de objeto asignado.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "El tipo de un parámetro de signatura de índice debe ser \"string\" o \"number\".", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Una interfaz solo puede extender un identificador o nombre completo con argumentos de tipo opcional.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Una interfaz solo puede extender una clase u otra interfaz.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "No se pueden importar archivos de declaración de tipos. Considere importar \"{0}\" en lugar de \"{1}\".", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "No se puede inicializar la variable '{0}' de ámbito externo en el mismo ámbito que la declaración '{1}' con ámbito de bloque.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "No se puede invocar una expresión con un tipo sin signatura de llamada. El tipo '{0}' no tiene ninguna signatura de llamada compatible.", + "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_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}'.", @@ -246,6 +253,7 @@ "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_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_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.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "No se encontró ningún archivo de declaración para el módulo '{0}'. '{1}' tiene un tipo \"any\" de forma implícita.", @@ -310,6 +318,7 @@ "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.", "Enable_tracing_of_the_name_resolution_process_6085": "Habilitar seguimiento del proceso de resolución de nombres.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Permite emitir interoperabilidad entre módulos CommonJS y ES mediante la creación de objetos de espacio de nombres para todas las importaciones. Implica \"allowSyntheticDefaultImports\".", "Enables_experimental_support_for_ES7_async_functions_6068": "Habilita la compatibilidad experimental con las funciones asincrónicas de ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Habilita la compatibilidad experimental con los elementos Decorator de ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita la compatibilidad experimental para emitir metadatos de tipo para los elementos Decorator.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "El prefijo coincidente más largo para \"{0}\" es \"{1}\".", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Buscando en la carpeta \"node_modules\", ubicación inicial: \"{0}\".", "Make_super_call_the_first_statement_in_the_constructor_90002": "Hacer que la llamada a \"super()\" sea la primera instrucción del constructor", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "El tipo de objeto asignado tiene implícitamente un tipo de plantilla \"any\".", "Member_0_implicitly_has_an_1_type_7008": "El miembro '{0}' tiene un tipo '{1}' implícitamente.", "Merge_conflict_marker_encountered_1185": "Se encontró un marcador de conflicto de combinación.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La declaración combinada '{0}' no puede incluir una declaración de exportación predeterminada. Considere la posibilidad de agregar una declaración \"export default {0}\" independiente en su lugar.", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propiedad \"{0}\" no tiene inicializador y no está asignada de forma definitiva en el constructor.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso get le falta una anotación de tipo de valor devuelto.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propiedad '{0}' tiene el tipo 'any' de forma implícita, porque a su descriptor de acceso set le falta una anotación de tipo de parámetro.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar a la misma propiedad del tipo base \"{2}\".", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propiedad \"{0}\" del tipo \"{1}\" no se puede asignar al tipo \"{2}\".", "Property_0_is_declared_but_its_value_is_never_read_6138": "La propiedad \"{0}\" se declara, pero su valor no se lee nunca.", "Property_0_is_incompatible_with_index_signature_2530": "La propiedad '{0}' es incompatible con la signatura de índice.", @@ -637,6 +648,7 @@ "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.", "Remove_declaration_for_Colon_0_90004": "Quitar declaración de: \"{0}\"", + "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.", "Report_errors_in_js_files_8019": "Notifique los errores de los archivos .js.", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "Literal de plantilla sin terminar.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Las llamadas a función sin tipo no pueden aceptar argumentos de tipo.", "Unused_label_7028": "Etiqueta no usada.", + "Use_synthetic_default_member_95016": "Use el miembro sintético \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "El uso de una cadena en una instrucción \"for...of\" solo se admite en ECMAScript 5 y versiones posteriores.", "VERSION_6036": "VERSIÓN", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "El valor de tipo \"{0}\" no tiene propiedades en común con el tipo \"{1}\". ¿Realmente quiere llamarlo?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Las declaraciones \"const\" deben inicializarse.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor no finito.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "El inicializador de miembros de enumeración \"const\" se evaluó con un valor \"NaN\" no permitido.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Las enumeraciones \"const\" solo se pueden usar en expresiones de acceso de propiedad o índice, o en la parte derecha de una declaración de importación o una asignación de exportación.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Las enumeraciones \"const\" solo se pueden usar en expresiones de acceso de propiedad o índice, o en la parte derecha de una declaración de importación, una asignación de exportación o una consulta de tipo.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "No se puede llamar a \"delete\" en un identificador en modo strict.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "\"enum declarations\" solo se puede usar en un archivo .ts.", "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" solo se puede usar en un archivo .ts.", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 81e9bebecc9..313315aa7b0 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Une déclaration d'espace de noms ne peut pas se trouver dans un autre fichier que celui d'une classe ou d'une fonction avec laquelle elle est fusionnée.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Une déclaration d'espace de noms ne peut pas se trouver avant une classe ou une fonction avec laquelle elle est fusionnée.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Une déclaration d'espace de noms est autorisée uniquement dans un espace de noms ou un module.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Impossible d'appeler ou de construire une importation de style d'espace de noms, ce qui va entraîner un échec au moment de l'exécution.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un initialiseur de paramètre est uniquement autorisé dans une implémentation de fonction ou de constructeur.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Impossible de déclarer une propriété de paramètre à l'aide d'un paramètre rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Une propriété de paramètre est uniquement autorisée dans une implémentation de constructeur.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Les accesseurs sont uniquement disponibles quand EcmaScript 5 ou version supérieure est ciblé.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Les accesseurs doivent être abstraits ou non abstraits.", "Add_0_to_existing_import_declaration_from_1_90015": "Ajouter '{0}' à la déclaration d'importation existante de \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Ajouter le modificateur async dans la fonction conteneur", "Add_index_signature_for_property_0_90017": "Ajouter une signature d'index pour la propriété '{0}'", "Add_missing_super_call_90001": "Ajouter l'appel manquant à 'super()'", "Add_this_to_unresolved_variable_90008": "Ajouter 'this.' à la variable non résolue", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un paramètre de signature d'index ne peut pas avoir de modificateur d'accessibilité.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un paramètre de signature d'index ne peut pas avoir d'initialiseur.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un paramètre de signature d'index doit avoir une annotation de type.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Un type de paramètre de signature d'index ne peut pas être un alias de type. Écrivez '[{0}: {1}]: {2}' à la place.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Un type de paramètre de signature d'index ne peut pas être un type union. Utilisez un type d'objet mappé à la place.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Le type d'un paramètre de signature d'index doit être 'string' ou 'number'.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Une interface peut uniquement étendre un identificateur/nom qualifié avec des arguments de type facultatifs.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Une interface peut uniquement étendre une classe ou une autre interface.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Impossible d'importer les fichiers de déclaration de type. Importez '{0}' à la place de '{1}'.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Impossible d'initialiser la variable de portée externe '{0}' dans la même portée que celle de la déclaration de portée de bloc '{1}'.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Impossible d'appeler une expression dont le type n'a pas de signature d'appel. Le type '{0}' n'a aucune signature d'appel compatible.", + "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_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}'.", @@ -246,6 +253,7 @@ "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_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_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}.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Le fichier de déclaration du module '{0}' est introuvable. '{1}' a implicitement un type 'any'.", @@ -310,6 +318,7 @@ "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.", "Enable_tracing_of_the_name_resolution_process_6085": "Activez le traçage du processus de résolution de noms.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Active l'interopérabilité entre les modules CommonJS et ES via la création d'objets d'espace de noms pour toutes les importations. Implique 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Active la prise en charge expérimentale des fonctions async ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Active la prise en charge expérimentale des éléments décoratifs ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Active la prise en charge expérimentale pour l'émission des métadonnées de type pour les éléments décoratifs.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "Le préfixe correspondant le plus long pour '{0}' est '{1}'.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Recherche dans le dossier 'node_modules', emplacement initial '{0}'.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Faire de l'appel à 'super()' la première instruction du constructeur", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Le type d'objet mappé a implicitement un type de modèle 'any'.", "Member_0_implicitly_has_an_1_type_7008": "Le membre '{0}' possède implicitement un type '{1}'.", "Merge_conflict_marker_encountered_1185": "Marqueur de conflit de fusion rencontré.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La déclaration fusionnée '{0}' ne peut pas inclure de déclaration d'exportation par défaut. Ajoutez plutôt une déclaration 'export default {0}' distincte.", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La propriété '{0}' n'a aucun initialiseur et n'est pas définitivement assignée dans le constructeur.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La propriété '{0}' a implicitement le type 'any', car son accesseur get ne dispose pas d'une annotation de type de retour.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La propriété '{0}' a implicitement le type 'any', car son accesseur set ne dispose pas d'une annotation de type de paramètre.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Impossible d'assigner la propriété '{0}' du type '{1}' à la même propriété du type de base '{2}'.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La propriété '{0}' du type '{1}' ne peut pas être assignée au type '{2}'.", "Property_0_is_declared_but_its_value_is_never_read_6138": "La propriété '{0}' est déclarée mais sa valeur n'est jamais lue.", "Property_0_is_incompatible_with_index_signature_2530": "La propriété '{0}' est incompatible avec la signature d'index.", @@ -637,6 +648,7 @@ "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.", "Remove_declaration_for_Colon_0_90004": "Supprimer la déclaration pour : '{0}'", + "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.", "Report_errors_in_js_files_8019": "Signalez les erreurs dans les fichiers .js.", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "Littéral de modèle inachevé.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Les appels de fonctions non typées ne peuvent pas accepter d'arguments de type.", "Unused_label_7028": "Étiquette inutilisée.", + "Use_synthetic_default_member_95016": "Utilisez un membre 'default' synthétique.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'utilisation d'une chaîne dans une instruction 'for...of' est prise en charge uniquement dans ECMAScript 5 et version supérieure.", "VERSION_6036": "VERSION", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "La valeur de type '{0}' n'a aucune propriété en commun avec le type '{1}'. Voulez-vous vraiment l'appeler ?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Les déclarations 'const' doivent être initialisées.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'initialiseur de membre enum 'const' donne une valeur non finie.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'initialiseur de membre enum 'const' donne une valeur non autorisée 'NaN'.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Les enums 'const' ne peuvent être utilisés que dans les expressions d'accès à une propriété ou un index, ou dans la partie droite d'une déclaration d'importation ou d'une assignation d'exportation.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Les enums 'const' ne peuvent être utilisés que dans les expressions d'accès à une propriété ou un index, ou dans la partie droite d'une déclaration d'importation, d'une assignation d'exportation ou d'une requête de type.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' ne peut pas être appelé dans un identificateur en mode strict.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Les déclarations 'enum' peuvent uniquement être utilisées dans un fichier .ts.", "export_can_only_be_used_in_a_ts_file_8003": "'export=' peut uniquement être utilisé dans un fichier .ts.", diff --git a/lib/it/diagnosticMessages.generated.json b/lib/it/diagnosticMessages.generated.json index bb0e5c3dcc7..e52f44a50d3 100644 --- a/lib/it/diagnosticMessages.generated.json +++ b/lib/it/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Una dichiarazione di spazio dei nomi non può essere presente in un file diverso rispetto a una classe o funzione con cui è stato eseguito il merge.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Una dichiarazione di spazio dei nomi non può essere specificata prima di una classe o funzione con cui è stato eseguito il merge.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Una dichiarazione di spazio dei nomi è consentita solo in uno spazio dei nomi o in un modulo.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Non è possibile chiamare o costruire un'importazione in stile spazio dei nomi. Questo comporterà un errore in fase di runtime.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Un inizializzatore di parametro è consentito solo in un'implementazione di funzione o costruttore.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Non è possibile dichiarare una proprietà di parametro usando un parametro REST.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Una proprietà di parametro è consentita solo in un'implementazione di costruttore.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Le funzioni di accesso sono disponibili solo se destinate a ECMAScript 5 e versioni successive.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Le funzioni di accesso devono essere tutte astratte o tutte non astratte.", "Add_0_to_existing_import_declaration_from_1_90015": "Aggiungere '{0}' alla dichiarazione di importazione esistente da \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Aggiungere il modificatore async alla funzione contenitore", "Add_index_signature_for_property_0_90017": "Aggiungere la firma dell'indice per la proprietà '{0}'", "Add_missing_super_call_90001": "Aggiungere la chiamata mancante a 'super()'", "Add_this_to_unresolved_variable_90008": "Aggiungere 'this.' alla variabile non risolta", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Un parametro della firma dell'indice non può contenere un modificatore di accessibilità.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Un parametro della firma dell'indice non può contenere un inizializzatore.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Un parametro della firma dell'indice deve contenere un'annotazione di tipo.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Un tipo di parametro della firma dell'indice non può essere un alias di tipo. Provare a scrivere '[{0}: {1}]: {2}'.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Un tipo di parametro della firma dell'indice non può essere un tipo di unione. Provare a usare un tipo di oggetto con mapping.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Il tipo di un parametro della firma dell'indice deve essere 'string' o 'number'.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Un'interfaccia può estendere solo un identificatore/nome qualificato con argomenti tipo facoltativi.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Un'interfaccia può estendere solo una classe o un'altra interfaccia.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Non è possibile importare file di dichiarazione di tipo. Provare a importare '{0}' invece di '{1}'.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Non è possibile inizializzare la variabile con ambito esterna '{0}' nello stesso ambito della dichiarazione con ambito del blocco '{1}'.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Non è possibile richiamare un'espressione al cui tipo manca una firma di chiamata. Per il tipo '{0}' non esistono firme di chiamata compatibili.", + "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_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}'.", @@ -246,6 +253,7 @@ "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_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_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.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Non è stato trovato alcun file di dichiarazione per il modulo '{0}'. A '{1}' è assegnato implicitamente un tipo 'any'.", @@ -310,6 +318,7 @@ "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.", "Enable_tracing_of_the_name_resolution_process_6085": "Abilita la traccia del processo di risoluzione dei nomi.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Abilita l'interoperabilità di creazione tra moduli ES e CommonJS tramite la creazione di oggetti spazio dei nomi per tutte le importazioni. Implica 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Abilita il supporto sperimentale per le funzioni asincrone di ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Abilita il supporto sperimentale per le espressioni Decorator di ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Abilita il supporto sperimentale per la creazione dei metadati dei tipi per le espressioni Decorator.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "Il prefisso di corrispondenza più lungo per '{0}' è '{1}'.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Verrà eseguita la ricerca nella cartella 'node_modules'. Percorso iniziale: '{0}'.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Impostare la chiamata a 'super()' come prima istruzione nel costruttore", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Il tipo di oggetto con mapping contiene implicitamente un tipo di modello 'any'.", "Member_0_implicitly_has_an_1_type_7008": "Il membro '{0}' contiene implicitamente un tipo '{1}'.", "Merge_conflict_marker_encountered_1185": "È stato rilevato un indicatore di conflitti di merge.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "La dichiarazione '{0}' sottoposta a merge non può includere una dichiarazione di esportazione predefinita. Provare ad aggiungere una dichiarazione 'export default {0}' distinta.", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "La proprietà '{0}' non include alcun inizializzatore e non viene assolutamente assegnata nel costruttore.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso get manca un'annotazione di tipo restituito.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "La proprietà '{0}' contiene implicitamente il tipo 'any', perché nella relativa funzione di accesso set manca un'annotazione di tipo di parametro.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "La proprietà '{0}' nel tipo '{1}' non è assegnabile alla stessa proprietà nel tipo di base '{2}'.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "La proprietà '{0}' nel tipo '{1}' non è assegnabile al tipo '{2}'.", "Property_0_is_declared_but_its_value_is_never_read_6138": "La proprietà '{0}' è dichiarata, ma il suo valore non viene mai letto.", "Property_0_is_incompatible_with_index_signature_2530": "La proprietà '{0}' non è compatibile con la firma dell'indice.", @@ -637,6 +648,7 @@ "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.", "Remove_declaration_for_Colon_0_90004": "Rimuovere la dichiarazione per '{0}'", + "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.", "Report_errors_in_js_files_8019": "Segnala gli errori presenti nei file con estensione js.", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "Valore letterale di modello senza terminazione.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Le chiamate di funzione non tipizzate potrebbero non accettare argomenti tipo.", "Unused_label_7028": "Etichetta non usata.", + "Use_synthetic_default_member_95016": "Usare il membro 'default' sintetico.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "L'uso di una stringa in un'istruzione 'for...of' è supportato solo in ECMAScript 5 e versioni successive.", "VERSION_6036": "VERSIONE", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Il valore di tipo '{0}' non ha proprietà in comune con il tipo '{1}'. Si intendeva chiamarlo?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Le dichiarazioni 'const' devono essere inizializzate.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "L'inizializzatore del membro di enumerazione 'const' è stato valutato come valore non finito.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "L'inizializzatore del membro di enumerazione 'const' è stato valutato come valore non consentito 'NaN'.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Le enumerazioni 'const' possono essere usate solo in espressioni di accesso a proprietà o indice oppure nella parte destra di un'assegnazione di esportazione o di una dichiarazione di importazione.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Le enumerazioni 'const' possono essere usate solo in espressioni di accesso a proprietà o indice oppure nella parte destra di un'assegnazione di esportazione, di una dichiarazione di importazione o di una query su tipo.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Non è possibile chiamare 'delete' su un identificatore in modalità strict.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' può essere usato solo in un file con estensione ts.", "export_can_only_be_used_in_a_ts_file_8003": "'export=' può essere usato solo in un file con estensione ts.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index b37eea15fdf..a02d6e57d7e 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "名前空間宣言は、それとマージするクラスや関数と異なるファイルに配置できません。", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "名前空間宣言は、それとマージするクラスや関数より前に配置できません。", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "名前空間宣言は、名前空間かモジュールでのみ使用できます。", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "名前空間スタイルのインポートを呼び出したり、構築したりすることはできません。実行時にエラーが発生する原因となります。", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "パラメーター初期化子は、関数またはコンストラクターの実装でのみ指定できます。", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "パラメーター プロパティは、rest パラメーターを使用して宣言することはできません。", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "パラメーター プロパティは、コンストラクターの実装でのみ指定できます。", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "アクセサーは ECMAScript 5 以上をターゲットにする場合にのみ使用できます。", "Accessors_must_both_be_abstract_or_non_abstract_2676": "アクセサーはどちらも抽象または非抽象である必要があります。", "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\" から既存のインポート宣言に '{0}' を追加する", + "Add_async_modifier_to_containing_function_90029": "含まれている関数に async 修飾子を追加します", "Add_index_signature_for_property_0_90017": "プロパティ '{0}' のインデックス シグネチャを追加する", "Add_missing_super_call_90001": "欠落している 'super()' 呼び出しを追加する", "Add_this_to_unresolved_variable_90008": "'this.' を未解決の変数に追加する", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "インデックス シグネチャのパラメーターにアクセシビリティ修飾子を指定することはできません。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "インデックス シグネチャのパラメーターに初期化子を指定することはできません。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "インデックス シグネチャのパラメーターには型の注釈が必要です。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "インデックス シグネチャのパラメーターの型を型のエイリアスにすることはできません。代わりに、'[{0}: {1}]: {2}' と記述することをご検討ください。", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "インデックス シグネチャのパラメーターの型を共用体型にすることはできません。代わりに、マップされたオブジェクト型の使用をご検討ください。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "インデックス シグネチャのパラメーターの型は 'string' または 'number' でなければなりません。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "インターフェイスが拡張するのは、オプションの型引数が指定された識別子/完全修飾名のみです。", "An_interface_may_only_extend_a_class_or_another_interface_2312": "インターフェイスで拡張できるのは、クラスまたは他のインターフェイスのみです。", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "型宣言ファイルをインポートできません。'{1}' の代わりに '{0}' をインポートすることを検討してください。", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "ブロック スコープ宣言 '{1}' と同じスコープ内の外部スコープ変数 '{0}' を初期化できません。", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "型に呼び出しシグネチャがない式を呼び出すことはできません。型 '{0}' には互換性のある呼び出しシグネチャがありません。", + "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_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}' を再宣言することはできません。", @@ -246,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "包含するファイルが指定されていないため、ルート ディレクトリを決定できません。'node_modules' フォルダーのルックアップをスキップします。", "Convert_function_0_to_class_95002": "関数 '{0}' をクラスに変換します", "Convert_function_to_an_ES2015_class_95001": "関数を ES2015 クラスに変換します", + "Convert_to_ES6_module_95017": "ES6 モジュールに変換します", "Convert_to_default_import_95013": "既定のインポートに変換する", "Corrupted_locale_file_0_6051": "ロケール ファイル {0} は破損しています。", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "モジュール '{0}' の宣言ファイルが見つかりませんでした。'{1}' は暗黙的に 'any' 型になります。", @@ -310,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "クラス内のプロパティの初期化の厳密なチェックを有効にします。", "Enable_strict_null_checks_6113": "厳格な null チェックを有効にします。", "Enable_tracing_of_the_name_resolution_process_6085": "名前解決の処理のトレースを有効にします。", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "すべてのインポートの名前空間オブジェクトを作成して、CommonJS と ES モジュール間の生成の相互運用性を有効にします。'allowSyntheticDefaultImports' を暗黙のうちに表します。", "Enables_experimental_support_for_ES7_async_functions_6068": "ES7 非同期関数用の実験的なサポートを有効にします。", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 デコレーター用の実験的なサポートを有効にします。", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "デコレーター用の型メタデータを発行するための実験的なサポートを有効にします。", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "'{0}' の一致する最長プレフィックスは '{1}' です。", "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' フォルダーを検索しています。最初の場所は '{0}' です。", "Make_super_call_the_first_statement_in_the_constructor_90002": "'super()' 呼び出しをコンストラクター内の最初のステートメントにする", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "マップされたオブジェクト型のテンプレートの型は暗黙的に 'any' になります。", "Member_0_implicitly_has_an_1_type_7008": "メンバー '{0}' の型は暗黙的に '{1}' になります。", "Merge_conflict_marker_encountered_1185": "マージ競合マーカーが検出されました。", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "マージされた宣言 '{0}' に既定のエクスポート宣言を含めることはできません。代わりに、'export default {0}' 宣言を別個に追加することを検討してください。", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "プロパティ '{0}' に初期化子がなく、コンストラクターで明確に割り当てられていません。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。get アクセサーには戻り値の型の注釈がないためです。", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "プロパティ '{0}' には型 'any' が暗黙的に設定されています。set アクセサーにはパラメーター型の注釈がないためです。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "型 '{1}' のプロパティ '{0}' を基本データ型 '{2}' の同じプロパティに割り当てることはできません。", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "型 '{1}' のプロパティ '{0}' を型 '{2}' に割り当てることはできません。", "Property_0_is_declared_but_its_value_is_never_read_6138": "プロパティ '{0}' が宣言されていますが、その値が読み取られることはありません。", "Property_0_is_incompatible_with_index_signature_2530": "プロパティ '{0}' はインデックス シグネチャと互換性がありません。", @@ -637,6 +648,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "暗黙的な 'any' 型を持つ 'this' 式でエラーが発生します。", "Redirect_output_structure_to_the_directory_6006": "ディレクトリへ出力構造をリダイレクトします。", "Remove_declaration_for_Colon_0_90004": "次に対する宣言を削除する: '{0}'", + "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 のフォールスルーがある場合にエラーを報告します。", "Report_errors_in_js_files_8019": ".js ファイルのエラーを報告します。", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "未終了のテンプレート リテラルです。", "Untyped_function_calls_may_not_accept_type_arguments_2347": "型指定のない関数の呼び出しで型引数を使用することはできません。", "Unused_label_7028": "未使用のラベル。", + "Use_synthetic_default_member_95016": "合成 'default' メンバーを使用します。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' ステートメントでの文字列の使用は ECMAScript 5 以上でのみサポートされています。", "VERSION_6036": "バージョン", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "型 '{0}' の値には、型 '{1}' と共通のプロパティがありません。呼び出しますか?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "'const' 宣言は初期化する必要があります。", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列挙型メンバーの初期化子が、無限値に評価されました。", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列挙型メンバーの初期化子が、許可されない値 'NaN' に評価されました。", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、あるいはインポート宣言またはエクスポート割り当ての右辺にのみ使用できます。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列挙型は、プロパティまたはインデックスのアクセス式、インポート宣言またはエクスポートの割り当ての右辺、型のクエリにのみ使用できます。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "厳格モードでは 'delete' を識別子で呼び出すことはできません。", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'列挙型宣言' を使用できるのは .ts ファイル内のみです。", "export_can_only_be_used_in_a_ts_file_8003": "'export=' を使用できるのは .ts ファイル内のみです。", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index d44c0eb7c1a..c73788cab9f 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수와 다른 파일에 있을 수 없습니다,", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "네임스페이스 선언은 해당 선언이 병합된 클래스나 함수 앞에 있을 수 없습니다.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "네임스페이스 선언은 네임스페이스 또는 모듈에서만 사용할 수 있습니다.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "네임스페이스 스타일 가져오기를 호출하거나 생성할 수 없으며 런타임 시 오류가 발생합니다.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "매개 변수 이니셜라이저는 함수 또는 생성자 구현에서만 허용됩니다.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "rest 매개 변수를 사용하여 매개 변수 속성을 선언할 수 없습니다.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "매개 변수 속성은 생성자 구현에서만 허용됩니다.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "접근자는 ECMAScript 5 이상을 대상으로 지정할 때만 사용할 수 있습니다.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "접근자는 모두 추상이거나 비추상이어야 합니다.", "Add_0_to_existing_import_declaration_from_1_90015": "\"{1}\"에서 기존 가져오기 선언에 '{0}' 추가", + "Add_async_modifier_to_containing_function_90029": "포함된 함수에 async 한정자 추가", "Add_index_signature_for_property_0_90017": "'{0}' 속성에 대해 인덱스 시그니처 추가", "Add_missing_super_call_90001": "누락된 'super()' 호출 추가", "Add_this_to_unresolved_variable_90008": "확인되지 않은 변수에 'this.' 추가", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "인덱스 시그니처 매개 변수에는 액세스 가능성 한정자를 사용할 수 없습니다.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "인덱스 시그니처 매개 변수에는 이니셜라이저를 사용할 수 없습니다.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "인덱스 시그니처 매개 변수에는 형식 주석을 사용할 수 없습니다.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "인덱스 시그니처 매개 변수 형식은 형식 별칭일 수 없습니다. 대신 '[{0}: {1}]: {2}'을(를) 작성하세요.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "인덱스 시그니처 매개 변수 형식은 공용 구조체 형식일 수 없습니다. 대신 매핑된 개체 형식을 사용하세요.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "인덱스 시그니처 매개 변수 형식은 'string' 또는 'number'여야 합니다.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "인터페이스는 선택적 형식 인수가 포함된 식별자/정규화된 이름만 확장할 수 있습니다.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "인터페이스는 클래스 또는 다른 인터페이스만 확장할 수 있습니다.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "형식 선언 파일을 가져올 수 없습니다. '{1}' 대신 '{0}'을(를) 가져오세요.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "블록 범위 선언 '{1}'과(와) 동일한 범위 내에서 외부 범위 변수 '{0}'을(를) 초기화할 수 없습니다.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "형식에 호출 시그니처가 없는 식을 호출할 수 없습니다. '{0}' 형식에 호환되는 호출 시그니처가 없습니다.", + "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_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}'을(를) 다시 선언할 수 없습니다.", @@ -246,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "포함 파일이 지정되지 않았고 루트 디렉터리를 확인할 수 없어 'node_modules' 폴더 조회를 건너뜁니다.", "Convert_function_0_to_class_95002": "'{0}' 함수를 클래스로 변환", "Convert_function_to_an_ES2015_class_95001": "함수를 ES2015 클래스로 변환", + "Convert_to_ES6_module_95017": "ES6 모듈로 변환", "Convert_to_default_import_95013": "기본 가져오기로 변환", "Corrupted_locale_file_0_6051": "로캘 파일 {0}이(가) 손상되었습니다.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "모듈 '{0}'에 대한 선언 파일을 찾을 수 없습니다. '{1}'에는 암시적으로 'any' 형식이 포함됩니다.", @@ -310,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "클래스의 속성 초기화에 대해 엄격한 검사를 사용하도록 설정합니다.", "Enable_strict_null_checks_6113": "엄격한 null 검사를 사용하도록 설정하세요.", "Enable_tracing_of_the_name_resolution_process_6085": "이름 확인 프로세스 추적을 사용하도록 설정하세요.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "모든 가져오기에 대한 네임스페이스 개체를 만들어 CommonJS 및 ES 모듈 간의 내보내기 상호 운용성을 사용하도록 설정합니다. 'allowSyntheticDefaultImports'를 의미합니다.", "Enables_experimental_support_for_ES7_async_functions_6068": "ES7 비동기 함수에 대해 실험적 지원을 사용합니다.", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 데코레이터에 대해 실험적 지원을 사용합니다.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "데코레이터에 대한 형식 메타데이터를 내보내기 위해 실험적 지원을 사용합니다.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "'{0}'에 대해 일치하는 가장 긴 접두사는 '{1}'입니다.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' 폴더에서 찾고 있습니다. 초기 위치: '{0}'.", "Make_super_call_the_first_statement_in_the_constructor_90002": "생성자의 첫 번째 문을 'super()'로 호출", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "매핑된 개체 형식에는 'any' 템플릿 형식이 암시적으로 포함됩니다.", "Member_0_implicitly_has_an_1_type_7008": "'{0}' 멤버에는 암시적으로 '{1}' 형식이 포함됩니다.", "Merge_conflict_marker_encountered_1185": "병합 충돌 표식을 발견했습니다.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "병합된 선언 '{0}'에는 기본 내보내기 선언을 포함할 수 없습니다. 대신 별도의 'export default {0}' 선언을 추가하세요.", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "속성 '{0}'은(는) 이니셜라이저가 없고 생성자에 할당되어 있지 않습니다.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' 속성에는 해당 get 접근자에 반환 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' 속성에는 해당 set 접근자에 매개 변수 형식 주석이 없으므로 암시적으로 'any' 형식이 포함됩니다.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "'{1}' 형식의 '{0}' 속성을 기본 형식 '{2}'의 동일한 속성에 할당할 수 없습니다.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' 형식의 '{0}' 속성을 '{2}' 형식에 할당할 수 없습니다.", "Property_0_is_declared_but_its_value_is_never_read_6138": "속성 '{0}'이(가) 선언은 되었지만 해당 값이 읽히지는 않았습니다.", "Property_0_is_incompatible_with_index_signature_2530": "'{0}' 속성이 인덱스 시그니처와 호환되지 않습니다.", @@ -637,6 +648,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "암시된 'any' 형식이 있는 'this' 식에서 오류를 발생합니다.", "Redirect_output_structure_to_the_directory_6006": "출력 구조를 디렉터리로 리디렉션합니다.", "Remove_declaration_for_Colon_0_90004": "'{0}'에 대한 선언 제거", + "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에 대한 오류를 보고합니다.", "Report_errors_in_js_files_8019": ".js 파일의 오류를 보고합니다.", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "종결되지 않은 템플릿 리터럴입니다.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "형식화되지 않은 함수 호출에는 형식 인수를 사용할 수 없습니다.", "Unused_label_7028": "사용되지 않는 레이블입니다.", + "Use_synthetic_default_member_95016": "가상 '기본' 멤버를 사용합니다.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "ECMAScript 5 이상에서만 'for...of' 문에서 문자열을 사용할 수 있습니다.", "VERSION_6036": "버전", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "'{0}' 형식의 값에 '{1}' 형식과 공통된 속성이 없습니다. 속성을 호출하려고 했습니까?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "'const' 선언은 초기화해야 합니다.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 열거형 멤버 이니셜라이저가 무한 값에 대해 평가되었습니다.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 열거형 멤버 이니셜라이저가 허용되지 않은 'NaN' 값에 대해 평가되었습니다.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성 또는 인덱스 액세스 식 또는 내보내기 할당 또는 가져오기 선언의 오른쪽에서만 사용할 수 있습니다.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 열거형은 속성 또는 인덱스 액세스 식 또는 내보내기 할당 또는 가져오기 선언의 오른쪽 또는 형식 쿼리에서만 사용할 수 있습니다.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "strict 모드에서는 식별자에 대해 'delete'를 호출할 수 없습니다.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations'는 .ts 파일에서만 사용할 수 있습니다.", "export_can_only_be_used_in_a_ts_file_8003": "'export='는 .ts 파일에서만 사용할 수 있습니다.", diff --git a/lib/lib.es2017.object.d.ts b/lib/lib.es2017.object.d.ts index a806ae2bf05..65aa1f95928 100644 --- a/lib/lib.es2017.object.d.ts +++ b/lib/lib.es2017.object.d.ts @@ -23,7 +23,7 @@ interface ObjectConstructor { * Returns an array of values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - values(o: { [s: string]: T } | { [n: number]: T }): T[]; + values(o: { [s: string]: T } | ArrayLike): T[]; /** * Returns an array of values of the enumerable properties of an object @@ -35,7 +35,7 @@ interface ObjectConstructor { * Returns an array of key/values of the enumerable properties of an object * @param o Object that contains the properties and methods. This can be an object that you created or an existing Document Object Model (DOM) object. */ - entries(o: { [s: string]: T } | { [n: number]: T }): [string, T][]; + entries(o: { [s: string]: T } | ArrayLike): [string, T][]; /** * Returns an array of key/values of the enumerable properties of an object diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 5cb411109c3..610113e4303 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Deklaracja przestrzeni nazw nie może znajdować się w innym pliku niż klasa lub funkcja, z którą ją scalono.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Deklaracja przestrzeni nazw nie może występować przed klasą lub funkcją, z którą ją scalono.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Deklaracja przestrzeni nazw jest dozwolona tylko w przestrzeni nazw lub module.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Nie można wywołać lub skonstruować importu stylu przestrzeni nazw. Spowoduje to błąd w czasie wykonania.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Inicjator parametru jest dozwolony tylko w implementacji funkcji lub konstruktora.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Właściwości parametru nie można zadeklarować za pomocą parametru rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Właściwość parametru jest dozwolona tylko w implementacji konstruktora.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Metody dostępu są dostępne tylko wtedy, gdy jest używany język ECMAScript 5 lub nowszy.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Obie metody dostępu muszą być abstrakcyjne lub nieabstrakcyjne.", "Add_0_to_existing_import_declaration_from_1_90015": "Dodaj element „{0}” do istniejącej deklaracji importu z elementu „{1}”", + "Add_async_modifier_to_containing_function_90029": "Dodaj modyfikator asynchroniczny do funkcji zawierającej", "Add_index_signature_for_property_0_90017": "Dodaj sygnaturę indeksu dla właściwości „{0}”", "Add_missing_super_call_90001": "Dodaj brakujące wywołanie „super()”", "Add_this_to_unresolved_variable_90008": "Dodaj „this.” do nierozpoznanej zmiennej", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Parametr sygnatury indeksu nie może mieć modyfikatora dostępności.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Parametr sygnatury indeksu nie może mieć inicjatora.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Parametr sygnatury indeksu musi mieć adnotację typu.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Typ parametru sygnatury indeksu nie może być aliasem typu. Rozważ zastosowanie następującego zapisu: „[{0}: {1}]: {2}”.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Typ parametru sygnatury indeksu nie może być typem unii. Rozważ użycie zamiast niego mapowanego typu obiektu.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Parametr sygnatury indeksu musi być typu „string” lub „number”.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Interfejs może rozszerzać tylko identyfikator/nazwę kwalifikowaną z opcjonalnymi argumentami typu.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Interfejs może rozszerzać tylko klasę lub inny interfejs.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Nie można zaimportować plików deklaracji typu. Rozważ zaimportowanie „{0}” zamiast „{1}”.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Nie można zainicjować zmiennej „{0}” z zakresu zewnętrznego w tym samym zakresie co deklaracja „{1}” należąca do zakresu bloku.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Nie można wywołać wyrażenia, w którego typie nie ma sygnatury wywołania. Typ „{0}” nie ma zgodnych sygnatur wywołań.", + "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_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.", @@ -246,6 +253,7 @@ "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_function_0_to_class_95002": "Konwertuj funkcję „{0}” na klasę", "Convert_function_to_an_ES2015_class_95001": "Konwertuj funkcję na klasę ES2015", + "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}.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Nie można znaleźć pliku deklaracji dla modułu „{0}”. Element „{1}” ma niejawnie typ „any”.", @@ -310,6 +318,7 @@ "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.", "Enable_tracing_of_the_name_resolution_process_6085": "Włącz śledzenie procesu rozpoznawania nazw.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Umożliwia współdziałanie emitowania między modułami CommonJS i ES przez tworzenie obiektów przestrzeni nazw dla wszystkich importów. Implikuje użycie ustawienia „allowSyntheticDefaultImports”.", "Enables_experimental_support_for_ES7_async_functions_6068": "Umożliwia obsługę eksperymentalną funkcji asynchronicznych języka ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Umożliwia obsługę eksperymentalną elementów Decorator języka ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Umożliwia obsługę eksperymentalną emitowania metadanych typów elementów Decorator.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "Najdłuższy zgodny prefiks dla „{0}” to „{1}”.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Wyszukiwanie w folderze „node_modules”, początkowa lokalizacja: „{0}”.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Ustaw wywołanie „super()” jako pierwszą instrukcję w konstruktorze", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Zmapowany typ obiektu niejawnie ma typ szablonu „any”.", "Member_0_implicitly_has_an_1_type_7008": "Dla składowej „{0}” niejawnie określono typ „{1}”.", "Merge_conflict_marker_encountered_1185": "Napotkano znacznik konfliktu scalania.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Scalona deklaracja „{0}” nie może zawierać domyślnej deklaracji eksportu. Rozważ dodanie oddzielnej deklaracji „export default {0}” zamiast niej.", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Właściwość „{0}” nie ma inicjatora i nie jest na pewno przypisana w konstruktorze.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „get” nie ma adnotacji zwracanego typu.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Dla właściwości „{0}” niejawnie określono typ „any”, ponieważ jego metoda dostępu „set” nie ma adnotacji typu parametru.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Właściwości „{0}” w typie „{1}” nie można przypisać do tej samej właściwości w typie podstawowym „{2}”.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Właściwości „{0}” w typie „{1}” nie można przypisać do typu „{2}”.", "Property_0_is_declared_but_its_value_is_never_read_6138": "Właściwość „{0}” jest zadeklarowana, ale jej wartość nie jest nigdy odczytywana.", "Property_0_is_incompatible_with_index_signature_2530": "Właściwość „{0}” jest niezgodna z sygnaturą indeksu.", @@ -637,6 +648,7 @@ "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.", "Remove_declaration_for_Colon_0_90004": "Usuń deklarację dla: „{0}”", + "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.", "Report_errors_in_js_files_8019": "Zgłaszaj błędy w plikach js.", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "Niezakończony literał szablonu.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Wywołania funkcji bez typu nie mogą przyjmować argumentów typu.", "Unused_label_7028": "Nieużywana etykieta.", + "Use_synthetic_default_member_95016": "Użyj syntetycznej składowej „default”.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Używanie ciągu w instrukcji „for...of” jest obsługiwane tylko w języku ECMAScript 5 lub nowszym.", "VERSION_6036": "WERSJA", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Wartość typu „{0}” nie ma żadnych wspólnych właściwości z typem „{1}”. Czy jej wywołanie było zamierzone?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Konieczne jest zainicjowanie deklaracji „const”.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Wynikiem obliczenia inicjatora składowej wyliczenia ze specyfikatorem „const” jest wartość nieskończona.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Wynikiem obliczenia inicjatora składowej wyliczenia ze specyfikatorem „const” jest niedozwolona wartość „NaN”.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Wyliczenia ze specyfikatorem „const” mogą być używane tylko w wyrażeniach dostępu do indeksu lub właściwości albo po prawej stronie deklaracji importu lub przypisania eksportu.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Wyliczenia ze specyfikatorem „const” mogą być używane tylko w wyrażeniach dostępu do indeksu lub właściwości albo po prawej stronie deklaracji importu, przypisania eksportu lub typu zapytania.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Nie można wywołać elementu „delete” dla identyfikatora w trybie z ograniczeniami.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Deklaracji wyliczeń można używać tylko w pliku ts.", "export_can_only_be_used_in_a_ts_file_8003": "Ciągu „export=” można użyć tylko w pliku ts.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index a6578991e44..ab61f9213b2 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -49,6 +49,7 @@ declare namespace ts.server.protocol { DocCommentTemplate = "docCommentTemplate", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", + GetCombinedCodeFix = "getCombinedCodeFix", ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", @@ -411,6 +412,13 @@ declare namespace ts.server.protocol { 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; @@ -444,6 +452,14 @@ declare namespace ts.server.protocol { */ errorCodes?: ReadonlyArray; } + interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; + } interface ApplyCodeActionCommandRequestArgs { /** May also be an array of commands. */ command: {}; @@ -1186,7 +1202,7 @@ declare namespace ts.server.protocol { } interface CodeFixResponse extends Response { /** The code actions that are available */ - body?: CodeAction[]; + body?: CodeFixAction[]; } interface CodeAction { /** Description of the code action to display in the UI of the editor */ @@ -1196,6 +1212,17 @@ declare namespace ts.server.protocol { /** 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 { + /** + * 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?: {}; + } /** * Format and format on key response message. */ diff --git a/lib/pt-BR/diagnosticMessages.generated.json b/lib/pt-BR/diagnosticMessages.generated.json index d30c2909244..4ba4b037e24 100644 --- a/lib/pt-BR/diagnosticMessages.generated.json +++ b/lib/pt-BR/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Uma declaração de namespace não pode estar em um arquivo diferente de uma classe ou função com a qual ela é mesclada.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Uma declaração de namespace não pode estar localizada antes de uma classe ou função com a qual ela é mesclada.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Uma declaração de namespace só é permitida e um namespace ou módulo.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Uma importação de estilo do namespace não pode ser chamada nem construída e causará uma falha no tempo de execução.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Um inicializador de parâmetro só é permitido em uma implementação de função ou de construtor.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Uma propriedade de parâmetro não pode ser declarada usando um parâmetro rest.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Uma propriedade de parâmetro somente é permitida em uma implementação de construtor.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Os acessadores somente estão disponíveis no direcionamento para ECMAScript 5 e superior.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Acessadores devem ser abstratos ou não abstratos.", "Add_0_to_existing_import_declaration_from_1_90015": "Adicionar '{0}' à declaração de importação existente de \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Adicione o modificador assíncrono que contém a função", "Add_index_signature_for_property_0_90017": "Adicionar assinatura de índice para a propriedade '{0}'", "Add_missing_super_call_90001": "Adicionar chamada 'super()' ausente", "Add_this_to_unresolved_variable_90008": "Adicionar 'this.' a uma variável não resolvida", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Um parâmetro de assinatura de índice não pode ter um modificador de acessibilidade.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Um parâmetro de assinatura de índice não pode ter um inicializador.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Um parâmetro de assinatura de índice deve ter uma anotação de tipo.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Um tipo de parâmetro de assinatura de índice não pode ser um alias de tipo. Considere gravar ' [{0}: {1}]: {2}' em vez disso.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Um tipo de parâmetro de assinatura de índice não pode ser um tipo de união. Considere usar um tipo de objeto mapeado em vez disso.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Um tipo de parâmetro de assinatura de índice deve ser 'string' ou 'number'.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Uma interface só pode estender um identificador/nome qualificado com argumentos de tipo opcionais.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Uma interface só pode estender uma classe ou outra interface.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Não é possível importar arquivos de declaração de tipo. Considere a possibilidade de importar '{0}' em vez de '{1}'.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Não é possível inicializar a variável com escopo externo '{0}' no mesmo escopo que a declaração de escopo de bloco '{1}'.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Não é possível invocar uma expressão cujo tipo não tem uma assinatura de chamada. O tipo '{0}' não tem assinaturas de chamada compatíveis.", + "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_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}'.", @@ -246,6 +253,7 @@ "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_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_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.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Não foi possível localizar o arquivo de declaração para o módulo '{0}'. '{1}' tem implicitamente um tipo 'any'.", @@ -310,6 +318,7 @@ "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.", "Enable_tracing_of_the_name_resolution_process_6085": "Habilite o rastreio do processo de resolução de nome.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Permite emissão de interoperabilidade entre CommonJS e Módulos ES através da criação de objetos de namespace para todas as importações. Implica em 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Habilita o suporte experimental para funções assíncronas de ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Habilita o suporte experimental para decoradores ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Habilita o suporte experimental para a emissão de tipo de metadados para decoradores.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "O maior prefixo correspondente para '{0}' é '{1}'.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Pesquisando na pasta 'node_modules', local inicial '{0}'.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Tornar a chamada 'super()' a primeira instrução no construtor", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "O tipo de objeto mapeado implicitamente tem um tipo de modelo 'any'.", "Member_0_implicitly_has_an_1_type_7008": "O membro '{0}' implicitamente tem um tipo '{1}'.", "Merge_conflict_marker_encountered_1185": "Marcador de conflito de mesclagem encontrado.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "A declaração mesclada '{0}' não pode conter uma declaração de exportação padrão. Considere adicionar uma declaração 'export default {0}' independente.", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "A propriedade '{0}' não tem nenhum inicializador e não está definitivamente atribuída no construtor.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador get não tem uma anotação de tipo de retorno.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "A propriedade '{0}' tem implicitamente o tipo 'any' porque o acessador set não tem uma anotação de tipo de parâmetro.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "A propriedade '{0}' no tipo '{1}' não pode ser atribuída à mesma propriedade no tipo base '{2}'.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "A propriedade '{0}' no tipo '{1}' não pode ser atribuída ao tipo '{2}'.", "Property_0_is_declared_but_its_value_is_never_read_6138": "A propriedade '{0}' é declarada, mas seu valor nunca é lido.", "Property_0_is_incompatible_with_index_signature_2530": "A propriedade '{0}' é incompatível com a assinatura de índice.", @@ -637,6 +648,7 @@ "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.", "Remove_declaration_for_Colon_0_90004": "Remover declaração para: '{0}'", + "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.", "Report_errors_in_js_files_8019": "Relatar erros em arquivos .js.", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "Literal de modelo não finalizado.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Chamadas de função não tipadas não podem aceitar argumentos de tipo.", "Unused_label_7028": "Rótulo não utilizado.", + "Use_synthetic_default_member_95016": "Use o membro sintético 'padrão'.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Há suporte para o uso de uma cadeia de caracteres em uma instrução 'for...of' somente no ECMAScript 5 e superior.", "VERSION_6036": "VERSÃO", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "O valor do tipo '{0}' não tem propriedades em comum com o tipo '{1}'. Você queria chamá-lo?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Declarações 'const' devem ser inicializadas.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "O inicializador de membro de enumeração 'const' foi avaliado como um valor não finito.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "O inicializador de membro de enumeração 'const' foi avaliado como o valor não permitido 'NaN'.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Enumerações 'const' só podem ser usadas em expressões de acesso de índice ou propriedade, ou do lado direito de uma declaração de importação ou atribuição de exportação.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Enumerações 'const' só podem ser usadas em expressões de acesso de índice ou propriedade, ou então do lado direito de uma consulta de tipo, declaração de importação ou atribuição de exportação.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete' não pode ser chamado em um identificador no modo estrito.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' só podem ser usadas em um arquivo .ts.", "export_can_only_be_used_in_a_ts_file_8003": "'export=' só pode ser usado em um arquivo .ts.", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index e3006cb4aa9..b0c8e703c15 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Объявление пространства имен и класс или функция, с которыми оно объединено, не могут находится в разных файлах.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Объявление пространства имен не может располагаться раньше класса или функции, с которыми оно объединено.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Объявление пространства имен разрешено использовать только в пространстве имен или модуле.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Импорт стиля пространства имен не может быть вызван или создан и приведет к сбою во время выполнения.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Инициализатор параметра разрешено использовать только в реализации функции или конструктора.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Свойство параметра невозможно объявить с помощью параметра REST.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Свойство параметра допускается только в реализации конструктора.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Методы доступа доступны только при разработке для ECMAScript 5 и более поздних версий.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "Методы доступа должны быть абстрактными или неабстрактными.", "Add_0_to_existing_import_declaration_from_1_90015": "Добавьте \"{0}\" в существующее объявление импорта из \"{1}\"", + "Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию", "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"", "Add_missing_super_call_90001": "Добавьте отсутствующий вызов \"super()\"", "Add_this_to_unresolved_variable_90008": "Добавьте \"this.\" к неразрешенной переменной", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Параметра сигнатуры индекса не может содержать модификатор специальных возможностей.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Параметр сигнатуры индекса не может содержать инициализатор.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "У параметра сигнатуры индекса должна быть аннотация типа.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Тип параметра сигнатуры индекса не может быть псевдонимом типа. Вместо этого рекомендуется написать \"[{0}: {1}]: {2}\".", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Тип параметра сигнатуры индекса не может быть типом объединения. Рекомендуется использовать тип сопоставляемого объекта.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Параметр сигнатуры индекса должен иметь тип string или number.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Интерфейс может расширить только идентификатор или полное имя с дополнительными аргументами типа.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Интерфейс может расширять только класс или другой интерфейс.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Невозможно импортировать файлы объявления типа. Рекомендуется импортировать \"{0}\" вместо \"{1}\".", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Невозможно инициализировать переменную \"{0}\" с внешней областью видимости в той же области видимости, что и объявление \"{1}\" с областью видимости \"Блок\".", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Не удается вызвать выражение, в типе которого отсутствует сигнатура вызова. Тип \"{0}\" не содержит совместимые сигнатуры вызова.", + "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_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}\" с областью видимости \"Блок\".", @@ -246,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "Содержащий файл не указан, корневой каталог невозможно определить. Выполняется пропуск поиска в папке node_modules.", "Convert_function_0_to_class_95002": "Преобразование функции \"{0}\" в класс", "Convert_function_to_an_ES2015_class_95001": "Преобразование функции в класс ES2015", + "Convert_to_ES6_module_95017": "Преобразовать в модуль ES6", "Convert_to_default_import_95013": "Преобразовать в импорт по умолчанию", "Corrupted_locale_file_0_6051": "Поврежденный файл языкового стандарта \"{0}\".", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "Не удалось найти файл объявления модуля \"{0}\". \"{1}\" имеет неявный тип \"any\".", @@ -310,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "Включение строгой проверки инициализации свойств в классах.", "Enable_strict_null_checks_6113": "Включить строгие проверки NULL.", "Enable_tracing_of_the_name_resolution_process_6085": "Включить трассировку процесса разрешения имен.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Позволяет обеспечивать взаимодействие между модулями CommonJS и ES посредством создания объектов пространства имен для всех импортов. Подразумевает \"allowSyntheticDefaultImports\".", "Enables_experimental_support_for_ES7_async_functions_6068": "Включает экспериментальную поддержку для асинхронных функций ES7.", "Enables_experimental_support_for_ES7_decorators_6065": "Включает экспериментальную поддержку для декораторов ES7.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Включает экспериментальную поддержку для создания метаданных типа для декораторов.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "Самый длинный соответствующий префикс для \"{0}\": \"{1}\".", "Looking_up_in_node_modules_folder_initial_location_0_6125": "Поиск в папке node_modules; первоначальное расположение: \"{0}\".", "Make_super_call_the_first_statement_in_the_constructor_90002": "Сделайте вызов \"super()\" первой инструкцией в конструкторе", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Сопоставленный объект неявно имеет тип шаблона \"любой\".", "Member_0_implicitly_has_an_1_type_7008": "Элемент \"{0}\" неявно имеет тип \"{1}\".", "Merge_conflict_marker_encountered_1185": "Встретилась отметка о конфликте слияния.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "Объединенное объявление \"{0}\" не может включать объявление экспорта по умолчанию. Рекомендуется добавить вместо него отдельное объявление \"export default {0}\".", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "Свойство \"{0}\" не имеет инициализатора, и ему не гарантировано присваивание в конструкторе.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа get не задана заметка с типом возвращаемого значения.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "Свойство \"{0}\" неявно имеет тип \"все\", так как для его метода доступа set не задана заметка с типом параметра.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "Свойство \"{0}\" в типе \"{1}\" невозможно присвоить тому же свойству в базовом типе \"{2}\".", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "Свойство \"{0}\" в типе \"{1}\" не может быть присвоено типу \"{2}\".", "Property_0_is_declared_but_its_value_is_never_read_6138": "Свойство \"{0}\" объявлено, но его значение не было прочитано.", "Property_0_is_incompatible_with_index_signature_2530": "Свойство \"{0}\" несовместимо с сигнатурой индекса.", @@ -637,6 +648,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "Вызвать ошибку в выражениях this с неявным типом any.", "Redirect_output_structure_to_the_directory_6006": "Перенаправить структуру вывода в каталог.", "Remove_declaration_for_Colon_0_90004": "Удалите объявление: \"{0}\"", + "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.", "Report_errors_in_js_files_8019": "Сообщать об ошибках в JS-файлах.", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "Незавершенный литерал шаблона.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Вызовы функций без типов не могут принимать аргументы типов.", "Unused_label_7028": "Неиспользуемая метка.", + "Use_synthetic_default_member_95016": "Используйте искусственный элемент \"default\".", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "Использование строки для оператора for...of поддерживается только в ECMAScript 5 и более поздних версиях.", "VERSION_6036": "ВЕРСИЯ", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "Значение типа \"{0}\" не имеет общих свойств со значением типа \"{1}\". Вы хотели вызвать его?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "Объявления \"const\" должны быть инициализированы.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "Инициализатор элементов перечисления const был вычислен в неконечное значение.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "Инициализатор элементов перечисления const был вычислен в запрещенное значение NaN.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Перечисления const можно использовать только в выражениях доступа к свойствам или по индексу, а также в правой части объявления присваивания импорта или экспорта.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "Перечисления const можно использовать только в выражениях доступа к свойству или индексу, а также в правой части объявления импорта, присваивания экспорта или запроса типа.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "Невозможно вызвать оператор delete с идентификатором в строгом режиме.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Объявления перечислений могут использоваться только в TS-файле.", "export_can_only_be_used_in_a_ts_file_8003": "Элемент \"export=\" может использоваться только в TS-файле.", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 5fb3e52bee1..dab9dc51cb4 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden farklı bir dosyada olamaz.", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "Bir ad alanı bildirimi, birleştirildiği sınıf veya işlevden önce gelemez.", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "Ad alanı bildirimine yalnızca bir ad alanında veya modülde izin verilir.", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "Bir ad alanı stili içeri aktarma işlemi çağrılamadığından veya oluşturulamadığından çalışma zamanında hataya yol açacak.", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "Parametre başlatıcısına yalnızca bir işlevde veya oluşturucu uygulamasında izin verilir.", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "Parametre özelliği, rest parametresi kullanılarak bildirilemez.", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "Parametre özelliğine yalnızca bir oluşturucu uygulamasında izin verilir.", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "Erişimciler yalnızca ECMAScript 5 ve üzeri hedeflenirken kullanılabilir.", "Accessors_must_both_be_abstract_or_non_abstract_2676": "İki erişimci de soyut veya soyut olmayan olmalıdır.", "Add_0_to_existing_import_declaration_from_1_90015": "'{0}' öğesini \"{1}\" konumundaki mevcut içeri aktarma bildirimine ekle", + "Add_async_modifier_to_containing_function_90029": "İçeren işleve zaman uyumsuz değiştirici ekle", "Add_index_signature_for_property_0_90017": "'{0}' özelliği için dizin imzası ekle", "Add_missing_super_call_90001": "Eksik 'super()' çağrısını ekle", "Add_this_to_unresolved_variable_90008": "Çözümlenmemiş değişkene 'this.' ekle", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "Dizin imzası parametresi, bir erişilebilirlik değiştiricisine sahip olamaz.", "An_index_signature_parameter_cannot_have_an_initializer_1020": "Dizin imzası parametresi, bir başlatıcıya sahip olamaz.", "An_index_signature_parameter_must_have_a_type_annotation_1022": "Dizin imzası parametresi, bir tür ek açıklamasına sahip olmalıdır.", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "Dizin imzası parametre türü bir tür diğer adı olamaz. Bunun yerine '[{0}: {1}]: {2}' yazabilirsiniz.", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "Dizin imzası parametre türü bir birleşim türü olamaz. Bunun yerine eşlenen nesne türü kullanabilirsiniz.", "An_index_signature_parameter_type_must_be_string_or_number_1023": "Dizin imzası parametresi, 'string' veya 'number' türünde olmalıdır.", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "Bir arabirim, isteğe bağlı tür bağımsız değişkenleri ile yalnızca bir tanımlayıcıyı/tam adı genişletebilir.", "An_interface_may_only_extend_a_class_or_another_interface_2312": "Arabirim, yalnızca bir sınıfı veya başka bir arabirimi genişletebilir.", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "Tür bildirim dosyaları içeri aktarılamıyor. '{1}' yerine '{0}' dosyasını içeri aktarmanız önerilir.", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "Dış kapsamdaki '{0}' değişkeni, blok kapsamındaki '{1}' bildirimiyle aynı kapsamda başlatılamaz.", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "Türü bir çağrı imzasına sahip olmayan bir ifade çağrılamaz. '{0}' türünün uyumlu çağrı imzası yok.", + "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_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.", @@ -246,6 +253,7 @@ "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_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_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.", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "'{0}' modülü için bildirim dosyası bulunamadı. '{1}' örtülü olarak 'any' türüne sahip.", @@ -310,6 +318,7 @@ "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.", "Enable_tracing_of_the_name_resolution_process_6085": "Ad çözümleme işlemini izlemeyi etkinleştir.", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "Tüm içeri aktarma işlemleri için ad alanı nesnelerinin oluşturulması aracılığıyla CommonJS ile ES Modülleri arasında yayımlama birlikte çalışabilirliğine imkan tanır. Şu anlama gelir: 'allowSyntheticDefaultImports'.", "Enables_experimental_support_for_ES7_async_functions_6068": "Zaman uyumsuz ES7 işlevleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_ES7_decorators_6065": "ES7 dekoratörleri için deneysel desteği etkinleştirir.", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "Dekoratörlere tür meta verisi gönderme için deneysel desteği etkinleştirir.", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "'{0}' için eşleşen en uzun ön ek: '{1}'.", "Looking_up_in_node_modules_folder_initial_location_0_6125": "'node_modules' klasöründe aranıyor; ilk konum: '{0}'.", "Make_super_call_the_first_statement_in_the_constructor_90002": "Oluşturucudaki ilk deyime 'super()' tarafından çağrı yapılmasını sağla", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "Eşleştirilmiş nesne türü örtük olarak 'any' şablon türüne sahip.", "Member_0_implicitly_has_an_1_type_7008": "'{0}' üyesi örtük olarak '{1}' türüne sahip.", "Merge_conflict_marker_encountered_1185": "Birleştirme çakışması işaretçisiyle karşılaşıldı.", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "'{0}' birleştirilen bildirimi, varsayılan bir dışarı aktarma bildirimini içeremez. Bunun yerine ayrı bir 'export default {0}' bildirimi eklemeyi göz önünde bulundurun.", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "'{0}' özelliği başlatıcı içermiyor ve oluşturucuda kesin olarak atanmamış.", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "'{0}' özelliği, get erişimcisinin dönüş türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "'{0}' özelliği, set erişimcisinin parametre türü ek açıklaması olmadığı için örtük olarak 'any' türü içeriyor.", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "'{1}' türündeki '{0}' özelliği, '{2}' temel türündeki aynı özelliğe atanamaz.", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "'{1}' türündeki '{0}' özelliği, '{2}' türüne atanamaz.", "Property_0_is_declared_but_its_value_is_never_read_6138": "'{0}' özelliği bildirildi ancak değeri hiç okunmadı.", "Property_0_is_incompatible_with_index_signature_2530": "'{0}' özelliği, dizin imzasıyla uyumsuz.", @@ -637,6 +648,7 @@ "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.", "Remove_declaration_for_Colon_0_90004": "'{0}' bildirimini 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.", "Report_errors_in_js_files_8019": ".js dosyalarındaki hataları bildirin.", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "Sonlandırılmamış şablon sabit değeri.", "Untyped_function_calls_may_not_accept_type_arguments_2347": "Türü belirtilmemiş işlev çağrıları tür bağımsız değişkenlerini kabul etmeyebilir.", "Unused_label_7028": "Kullanılmayan etiket.", + "Use_synthetic_default_member_95016": "Yapay 'default' üyesini kullanın.", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "'for...of' deyiminde dize kullanma yalnızca ECMAScript 5 veya üzerinde desteklenir.", "VERSION_6036": "SÜRÜM", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "'{0}' türünün değeri ile '{1}' türü arasında hiç ortak özellik yok. Bunun yerine çağrı yapmak mı istediniz?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "'const' bildirimlerinin başlatılması gerekiyor.", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' sabit listesi üyesi başlatıcısı, sonlu olmayan bir değer olarak hesaplandı.", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' sabit listesi üyesi başlatıcısı, izin verilmeyen 'NaN' değeri olarak hesaplandı.", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' sabit listeleri yalnızca bir özellikte, dizin erişim ifadelerinde, içeri aktarma bildiriminin sağ tarafında veya dışarı aktarma atamasında kullanılabilir.", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' sabit listeleri yalnızca bir özellikte, dizin erişim ifadelerinde, içeri aktarma bildiriminin veya dışarı aktarma atamasının sağ tarafında ya da tür sorgusunda kullanılabilir.", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "'delete', katı moddaki bir tanımlayıcıda çağrılamaz.", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' yalnızca bir .ts dosyasında kullanılabilir.", "export_can_only_be_used_in_a_ts_file_8003": "'export=' yalnızca bir .ts dosyasında kullanılabilir.", diff --git a/lib/tsc.js b/lib/tsc.js index 8523e02817e..ef23d59ebc3 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -36,24 +36,6 @@ var ts; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); - var NodeBuilderFlags; - (function (NodeBuilderFlags) { - NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; - NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; - NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; - NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; - NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; - })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -150,7 +132,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.7"; - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -159,6 +141,7 @@ var ts; ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -284,6 +267,9 @@ var ts; } ts.forEach = forEach; function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -1294,6 +1280,8 @@ var ts; ts.returnTrue = returnTrue; function identity(x) { return x; } ts.identity = identity; + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; function notImplemented() { throw new Error("Not implemented"); } @@ -1621,7 +1609,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47) + if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92) return 3; } if (path.lastIndexOf("file:///", 0) === 0) { @@ -2277,10 +2265,10 @@ var ts; } function Signature() { } function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0; this.modifierFlagsCache = 0; this.transformFlags = 0; @@ -2407,9 +2395,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; function matchPatternOrExact(patternStrings, candidate) { @@ -2506,170 +2492,16 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - clearCache(); - } - else { - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - clearCache(); - } - else { - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } - } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -2910,7 +2742,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -3019,7 +2851,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -3604,6 +3441,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3863,7 +3701,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -3972,6 +3810,7 @@ var ts; Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), 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."), @@ -4081,7 +3920,6 @@ var ts; Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -5785,7 +5623,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -5808,15 +5645,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return str += " "; }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -5828,10 +5674,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -5872,6 +5718,12 @@ var ts; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -7116,41 +6968,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 && node.body && node.body.kind === 234 && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -7273,6 +7114,29 @@ var ts; return getAssignmentTargetKind(node) !== 0; } ts.isAssignmentTarget = isAssignmentTarget; + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208: + case 209: + case 221: + case 212: + case 222: + case 236: + case 261: + case 262: + case 223: + case 215: + case 216: + case 217: + case 213: + case 214: + case 225: + case 264: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -8000,7 +7864,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -8550,14 +8426,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0: return carriageReturnLineFeed; case 1: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; function formatEnum(value, enumObject, isFlags) { @@ -9530,7 +9406,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192; + return node.kind === 190; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -9974,7 +9850,7 @@ var ts; } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { - return ts.isIdentifier(node) && node.autoGenerateKind > 0; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7) > 0; } ts.isGeneratedIdentifier = isGeneratedIdentifier; function isModifierKind(token) { @@ -10700,8 +10576,8 @@ var ts; case 177: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 161: @@ -15064,7 +14940,6 @@ var ts; return result; } scanner.scanRange(start + 3, length - 5, function () { - var advanceToken = true; var state = 1; var margin = undefined; var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; @@ -15091,7 +14966,6 @@ var ts; removeTrailingNewlines(comments); parseTag(indent); state = 0; - advanceToken = false; margin = undefined; indent++; } @@ -15136,13 +15010,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - t = nextJSDocToken(); - } - else { - advanceToken = true; - t = currentToken; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -15226,7 +15094,8 @@ var ts; if (!tag) { return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -15250,6 +15119,7 @@ var ts; indent = 0; break; case 57: + scanner.setTextPos(scanner.getTextPos() - 1); case 1: break loop; case 5: @@ -15279,7 +15149,7 @@ var ts; } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281, atToken.pos); @@ -15287,8 +15157,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -15546,33 +15415,43 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0; + break; case "arg": case "argument": case "param": - return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -15591,6 +15470,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -17982,6 +17869,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180: return computePropertyAccess(node, subtreeFlags); + case 181: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -17990,13 +17879,15 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3; } if (subtreeFlags & 524288 - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 | 268435456))) { transformFlags |= 192; + if (expression.transformFlags & 268435456) { + transformFlags |= 16384; + } } if (expression.kind === 91) { transformFlags |= 67108864; @@ -18005,19 +17896,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97: - return true; - case 180: - case 181: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97; - } - return false; + return transformFlags & ~940049729; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18028,7 +17907,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; + return transformFlags & ~940049729; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18045,7 +17924,7 @@ var ts; transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18068,7 +17947,7 @@ var ts; transformFlags |= 192 | 131072; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18101,7 +17980,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + return transformFlags & ~942011713; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -18113,7 +17992,7 @@ var ts; transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + return transformFlags & ~942011713; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18129,7 +18008,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18140,7 +18019,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537920833; + return transformFlags & ~940574017; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -18148,7 +18027,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18160,7 +18039,7 @@ var ts; transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -18182,7 +18061,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18197,7 +18076,7 @@ var ts; transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; @@ -18205,7 +18084,7 @@ var ts; transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -18235,7 +18114,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + return transformFlags & ~1003935041; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18257,7 +18136,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + return transformFlags & ~1003935041; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -18276,17 +18155,27 @@ var ts; transformFlags |= 32768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601249089; + return transformFlags & ~1003902273; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (expressionKind === 97) { - transformFlags |= 16384; + if (transformFlags & 134217728) { + transformFlags ^= 134217728; + transformFlags |= 268435456; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~671089985; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; + if (expressionFlags & 134217728) { + transformFlags &= ~134217728; + transformFlags |= 268435456; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~671089985; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18298,7 +18187,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -18313,7 +18202,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18322,7 +18211,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18330,7 +18219,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -18338,7 +18227,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -18347,7 +18236,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~574674241; + return transformFlags & ~977327425; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432; @@ -18358,16 +18247,22 @@ var ts; transformFlags |= 192 | 4194304; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546309441; + return transformFlags & ~948962625; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 536872257; + var excludeFlags = 939525441; switch (kind) { case 120: case 192: transformFlags |= 8 | 16; break; + case 185: + case 203: + case 292: + transformFlags |= 3; + excludeFlags = 536872257; + break; case 114: case 112: case 113: @@ -18376,8 +18271,6 @@ var ts; case 76: case 233: case 268: - case 185: - case 203: case 204: case 131: transformFlags |= 3; @@ -18475,7 +18368,8 @@ var ts; transformFlags |= 8 | 1048576; break; case 97: - transformFlags |= 192; + transformFlags |= 192 | 134217728; + excludeFlags = 536872257; break; case 99: transformFlags |= 16384; @@ -18485,11 +18379,11 @@ var ts; if (subtreeFlags & 524288) { transformFlags |= 8 | 1048576; } - excludeFlags = 537396545; + excludeFlags = 940049729; break; case 176: transformFlags |= 192 | 8388608; - excludeFlags = 537396545; + excludeFlags = 940049729; break; case 177: transformFlags |= 192; @@ -18501,7 +18395,7 @@ var ts; transformFlags |= 3 | 4096; break; case 179: - excludeFlags = 540087617; + excludeFlags = 942740801; if (subtreeFlags & 2097152) { transformFlags |= 192; } @@ -18514,7 +18408,7 @@ var ts; break; case 178: case 183: - excludeFlags = 537396545; + excludeFlags = 940049729; if (subtreeFlags & 524288) { transformFlags |= 192; } @@ -18549,27 +18443,27 @@ var ts; case 182: case 183: case 178: - return 537396545; + return 940049729; case 234: - return 574674241; + return 977327425; case 147: - return 536872257; + return 939525441; case 188: - return 601249089; + return 1003902273; case 187: case 229: - return 601281857; + return 1003935041; case 228: - return 546309441; + return 948962625; case 230: case 200: - return 539358529; + return 942011713; case 153: - return 601015617; + return 1003668801; case 152: case 154: case 155: - return 601015617; + return 1003668801; case 119: case 133: case 130: @@ -18588,14 +18482,23 @@ var ts; case 232: return -3; case 179: - return 540087617; + return 942740801; case 264: - return 537920833; + return 940574017; case 175: case 176: - return 537396545; - default: + return 940049729; + case 185: + case 203: + case 292: + case 186: + case 97: return 536872257; + case 180: + case 181: + return 671089985; + default: + return 939525441; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -19291,7 +19194,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -19305,6 +19210,30 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + function parseNodeModuleFromPath(path) { + path = ts.normalizePath(path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = removeExtensionAndIndex(path.slice(indexAfterPackageName + 1)); + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function removeExtensionAndIndex(path) { + var noExtension = ts.removeFileExtension(path); + return noExtension === "index" ? "" : ts.removeSuffix(noExtension, "/index"); + } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); } @@ -19383,13 +19312,18 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -19532,13 +19466,17 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -19697,6 +19635,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -19730,10 +19673,25 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { @@ -19828,7 +19786,12 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -19975,12 +19938,144 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - var _displayBuilder; var builtinGlobals = ts.createSymbolTable(); builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol); var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 | 8192, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 | 3112960 | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -19996,8 +20091,10 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { - getDiagnostics(sourceFile, cancellationToken); + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -21006,7 +21103,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -21373,6 +21470,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); return access.accessibility === 0; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455, false); + return access.accessibility === 0; + } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; @@ -21463,97 +21564,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4; } + var nodeFlags = 3112960; + if (flags & 2) { + nodeFlags |= 128; + } + if (flags & 1) { + nodeFlags |= 512; + } + var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, entity, sourceFile, writer); + return writer; + } } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144) { + sigOutput = kind === 1 ? 162 : 161; + } + else { + sigOutput = kind === 1 ? 157 : 156; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, sig, sourceFile, writer); + return writer; + } } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); - } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4, typeNode, sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608; + context.flags &= ~8388608; if (!type) { context.encounteredError = true; return undefined; @@ -21590,6 +21725,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024) { + if (!(context.flags & 1048576)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140, ts.createKeywordTypeNode(137)); } if (type.flags & 2048) { @@ -21611,10 +21751,13 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 32768 && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304) { + if (!context.encounteredError && !(context.flags & 32768)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -21627,7 +21770,7 @@ var ts; var name = type.symbol ? symbolToName(type.symbol, context, 793064, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } - if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + 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); @@ -21640,7 +21783,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144)) { context.encounteredError = true; } return undefined; @@ -21665,7 +21808,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1); @@ -21673,7 +21816,7 @@ var ts; function createAnonymousTypeNode(type) { var symbol = type.symbol; if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455); @@ -21692,10 +21835,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + 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; + } } } else { @@ -21710,7 +21859,8 @@ var ts; return declaration.parent.kind === 269 || declaration.parent.kind === 235; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return ts.contains(context.symbolStack, symbol); + return (!!(context.flags & 4096) || ts.contains(context.symbolStack, symbol)) && + (!(context.flags & 8) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); } } } @@ -21735,11 +21885,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024) ? 0 : 1); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, false); @@ -21752,7 +21902,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -21766,12 +21916,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -21861,9 +22016,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + if (context.flags & 2048) { + if (propertySymbol.flags & 4194304) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 | 16) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } var propertyType = ts.getCheckFlags(propertySymbol) & 2048 ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455); + } + } var propertyName = symbolToName(propertySymbol, context, 107455, true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; @@ -21904,11 +22074,21 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152)) { + context.encounteredError = true; + } return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); @@ -21927,7 +22107,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256) { if (returnTypeNode && returnTypeNode.kind === 119) { returnTypeNode = undefined; } @@ -21935,14 +22115,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var savedContextFlags = context.flags; + context.flags &= ~512; var name = symbolToName(type.symbol, context, 793064, true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -21953,7 +22136,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -21977,45 +22160,20 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64)) { chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 | 64 | 524288)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -22038,11 +22196,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 | 64 | 524288)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, predicate, sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -22098,6 +22338,9 @@ var ts; return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 && symbol.escapedName === "default") { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -22107,7 +22350,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072)) { context.encounteredError = true; } switch (declaration.kind) { @@ -22126,677 +22369,6 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91) { - writePunctuation(writer, 21); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91) { - writePunctuation(writer, 22); - } - } - else { - writePunctuation(writer, 23); - writer.writeSymbol(symbolName, symbol); - } - } - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - if (flags & 1) { - if (ts.getCheckFlags(symbol) & 1) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - var isTypeParameter = symbol.flags & 262144; - var typeFormatFlag = 256 & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 | 16384); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024; - if (type.flags & 33585807) { - writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 && !(type.flags & 131072)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 || type.flags & (272 | 32768)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 1024) && type.aliasSymbol && - ((flags & 65536) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 | 32)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024) { - if (flags & 131072) { - writeKeyword(writer, 140); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137); - } - else if (type.flags & 96) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288) { - if (flags & 128) { - writePunctuation(writer, 19); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128); - if (flags & 128) { - writePunctuation(writer, 20); - } - } - else if (type.flags & 1048576) { - writeType(type.objectType, 128); - writePunctuation(writer, 21); - writeType(type.indexType, 0); - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 17); - writeSpace(writer); - writePunctuation(writer, 24); - writeSpace(writer); - writePunctuation(writer, 18); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 ? 0 : 128); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - if (symbol.flags & 32 || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); - } - if (pos < end) { - writePunctuation(writer, 27); - writeType(typeArguments[pos], 512); - pos++; - while (pos < end) { - writePunctuation(writer, 26); - writeSpace(writer); - writeType(typeArguments[pos], 0); - pos++; - } - writePunctuation(writer, 29); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1)) { - writeType(typeArguments[0], 128 | 32768); - writePunctuation(writer, 21); - writePunctuation(writer, 22); - } - else if (type.target.objectFlags & 8) { - writePunctuation(writer, 21); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); - writePunctuation(writer, 22); - } - else if (flags & 16384 && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200) { - writeAnonymousType(type, flags); - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128) { - writePunctuation(writer, 19); - } - if (type.flags & 131072) { - writeTypeList(formatUnionTypes(type.types), 49); - } - else { - writeTypeList(type.types, 48); - } - if (flags & 128) { - writePunctuation(writer, 20); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - if (symbol.flags & 32 && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 && flags & 16384) || - symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); - } - else { - writeKeyword(writer, 119); - } - } - else { - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 && type.symbol && type.symbol.flags & 32; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192) && - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 || declaration.parent.kind === 235; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 4) || - ts.contains(symbolStack, symbol); - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 103); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); - if (typeFormatFlags & 32768) { - writePunctuation(writer, 20); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216) { - writePunctuation(writer, 55); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128) { - return true; - } - else if (flags & 512) { - var typeParameters = callSignature.target && (flags & 64) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17); - writePunctuation(writer, 18); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 94); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); - if (flags & 128) { - writePunctuation(writer, 20); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - var stringIndexInfo = resolved.objectFlags & 2048 && resolved.stringIndexInfo ? - createIndexInfo(anyType, resolved.stringIndexInfo.isReadonly, resolved.stringIndexInfo.declaration) : - resolved.stringIndexInfo; - buildIndexSignatureDisplay(stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384) { - if (p.flags & 4194304) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = ts.getCheckFlags(p) & 2048 ? anyType : getTypeOfSymbol(p); - if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56); - writeSpace(writer); - writeType(t, globalFlags & 16384); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0); - writePunctuation(writer, 22); - if (type.declaration.questionToken) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0); - writePunctuation(writer, 25); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 175) { - writePunctuation(writer, 17); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18); - } - else if (bindingPattern.kind === 176) { - writePunctuation(writer, 21); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26); - } - writePunctuation(writer, 22); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - var flags = 512; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - flags = 0; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99); - } - writeSpace(writer); - writeKeyword(writer, 126); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 && isTypeAny(returnType)) { - return; - } - if (flags & 16) { - writeSpace(writer); - writePunctuation(writer, 36); - } - else { - writePunctuation(writer, 56); - } - writeSpace(writer); - var typePredicate = getTypePredicateOfSignature(signature); - if (typePredicate) { - buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1) { - writeKeyword(writer, 94); - writeSpace(writer); - } - if (signature.target && (flags & 64)) { - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56); - writeSpace(writer); - switch (kind) { - case 1: - writeKeyword(writer, 133); - break; - case 0: - writeKeyword(writer, 136); - break; - } - writePunctuation(writer, 22); - writePunctuation(writer, 56); - writeSpace(writer); - if (info.type) { - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - } - else { - writeKeyword(writer, 119); - } - writePunctuation(writer, 25); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } function isDeclarationVisible(node) { if (node) { var links = getNodeLinks(node); @@ -22908,8 +22480,8 @@ var ts; function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { resolutionResults[i] = false; } return false; @@ -22943,6 +22515,10 @@ var ts; if (propertyName === 3) { return target.resolvedReturnType; } + if (propertyName === 4) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } function popTypeResolution() { @@ -23048,7 +22624,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); @@ -23738,7 +23315,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); return type.resolvedBaseTypes = ts.emptyArray; } if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { @@ -23778,7 +23355,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); } } else { @@ -24182,18 +23759,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -24683,12 +24261,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0)) { + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -24707,29 +24288,30 @@ var ts; return getResolvedBaseConstraint(type) !== circularConstraintType; } function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216) { var types = t.types; @@ -24749,7 +24331,7 @@ var ts; return stringType; } if (t.flags & 1048576) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -24765,7 +24347,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -25114,7 +24696,7 @@ var ts; function maybeAddJsSyntheticRestParameter(declaration, parameters) { var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -25391,12 +24973,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -25461,7 +25043,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, undefined, 1); + var typeStr = typeToString(type, undefined, 2); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { return unknownType; @@ -25955,8 +25537,8 @@ var ts; function getUnionTypePredicate(signatures) { var first; var types = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var sig = signatures_3[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred) { continue; @@ -26213,33 +25795,51 @@ var ts; } return false; } - function getTransformedIndexedAccessType(type) { + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 && getTemplateTypeFromMappedType(type) === neverType; + } + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - if (objectType.flags & 262144 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0)); - } - else { - regularTypes.push(t); + if (objectType.flags & 262144 && isGenericObjectType(objectType)) { + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + 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 getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 181) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { @@ -27054,7 +26654,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 64)); } enumRelation.set(id, false); return false; @@ -27181,8 +26781,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, undefined, 256); - targetType = typeToString(target, undefined, 256); + sourceType = typeToString(source, undefined, 64); + targetType = typeToString(target, undefined, 64); } if (!message) { if (relation === comparableRelation) { @@ -27636,8 +27236,11 @@ var ts; return result; } } - else if (target.flags & 1048576 && source.indexType === target.indexType) { + else if (target.flags & 1048576) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -28625,6 +28228,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -28635,6 +28239,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -28666,7 +28271,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -28710,7 +28315,9 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return inference.candidates ? getUnionType(inference.candidates, 2) : emptyObjectType; + return inference.candidates ? getUnionType(inference.candidates, 2) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -28729,6 +28336,7 @@ var ts; if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -28777,15 +28385,20 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - var p = priority | (source === implicitNeverType ? 16 : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -28807,15 +28420,15 @@ var ts; } } else if (source.flags & 524288 && target.flags & 524288) { - priority ^= 1; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2) && target.flags & 524288) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1; + contravariant = !contravariant; } else if (source.flags & 1048576 && target.flags & 1048576) { inferFromTypes(source.objectType, target.objectType); @@ -28837,7 +28450,7 @@ var ts; } if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2; + priority |= 1; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -28876,9 +28489,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -28908,7 +28521,7 @@ var ts; var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4; + priority |= 2; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -29026,10 +28639,16 @@ var ts; !hasPrimitiveConstraint(inference.typeParameter) && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = inference.priority & 1 ? getCommonSubtype(baseCandidates) : - context.flags & 1 || inference.priority & 8 ? getUnionType(baseCandidates, 2) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 || inference.priority & 4 ? + getUnionType(baseCandidates, 2) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + if (inferredType.flags & 16384 && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2) { inferredType = silentNeverType; @@ -29312,14 +28931,6 @@ var ts; return 8388607; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576) { - var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; - var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); - if (result !== baseConstraint) { - return result; - } - return type; - } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -30234,13 +29845,14 @@ var ts; var parent = node.parent; return parent.kind === 180 || parent.kind === 182 && parent.expression === node || - parent.kind === 181 && parent.expression === node; + parent.kind === 181 && parent.expression === node || + parent.kind === 204 || + parent.kind === 177 && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288); } - function getDeclaredOrApparentType(symbol, node) { - var type = getTypeOfSymbol(symbol); + function getApparentTypeForLocation(type, node) { if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } @@ -30305,7 +29917,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3)) { @@ -30498,6 +30110,14 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 187 && @@ -30528,10 +30148,6 @@ var ts; return type; } } - if (noImplicitThis) { - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -31065,7 +30681,7 @@ var ts; return node ? node.contextualMapper : identityMapper; } function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0); + var signatures = getSignaturesOfType(type, 0); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -31595,8 +31211,8 @@ var ts; } if (sourceAttributesType) { var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); @@ -32106,7 +31722,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } if (node.kind !== 180 || assignmentKind === 1 || @@ -32320,7 +31936,7 @@ var ts; } function isValidMethodAccess(method, type) { var propType = getTypeOfFuncClassEnumModule(method); - var signatures = getSignaturesOfType(propType, 0); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { var thisType = getThisTypeOfSignature(sig); @@ -32468,8 +32084,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var signature = signatures_5[_i]; + 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 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -32579,7 +32195,7 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -32604,7 +32220,7 @@ var ts; getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); } } var thisType = getThisTypeOfSignature(signature); @@ -32939,8 +32555,8 @@ var ts; else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -32950,8 +32566,8 @@ var ts; else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var sig = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -34108,6 +33724,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -35512,8 +35131,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_8 = signatures; _a < signatures_8.length; _a++) { - var signature = signatures_8[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -36402,7 +36021,13 @@ var ts; } if (ts.isBindingPattern(node.name)) { if (node.initializer && node.parent.parent.kind !== 216) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + } checkParameterInitializer(node); } return; @@ -36988,7 +36613,7 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -39037,20 +38662,20 @@ var ts; : unknownType; if (type.flags & 1024 && type.symbol === symbol) { - flags |= 131072; + flags |= 1048576; } - if (flags & 8192) { + if (flags & 131072) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -40119,12 +39744,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 || node.name.kind === 175) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } @@ -40530,7 +40158,7 @@ var ts; var node = createSynthesizedNode(71); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; - node.autoGenerateKind = 0; + node.autoGenerateFlags = 0; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -40545,20 +40173,23 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1; + name.autoGenerateFlags = 1; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16; + } return name; } ts.createTempVariable = createTempVariable; function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2; + name.autoGenerateFlags = 2; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -40566,7 +40197,7 @@ var ts; ts.createLoopVariable = createLoopVariable; function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3; + name.autoGenerateFlags = 3; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -40574,10 +40205,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4; + name.autoGenerateFlags = 4; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8; + } nextAutoGenerateId++; return name; } @@ -40869,11 +40502,12 @@ var ts; : node; } ts.updateIndexSignature = updateIndexSignature; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -43480,7 +43114,9 @@ var ts; } ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; function parenthesizeSubexpressionOfConditionalExpression(e) { - return e.kind === 195 && e.operatorToken.kind === 26 + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 && emittedExpression.operatorToken.kind === 26 || + emittedExpression.kind === 293 ? ts.createParen(e) : e; } @@ -43969,6 +43605,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -44078,7 +43715,7 @@ var ts; } switch (kind) { case 71: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145: @@ -45031,7 +44668,10 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + value = ensureIdentifier(flattenContext, value, false, location); + } + else if (needsValue) { value = ensureIdentifier(flattenContext, value, true, location); } else if (ts.nodeIsSynthesized(node)) { @@ -45061,6 +44701,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { var pendingExpressions; var pendingDeclarations = []; @@ -45077,6 +44737,13 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + initializer = ensureIdentifier(flattenContext, initializer, false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(undefined); @@ -45725,10 +45392,13 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16; + classAliases[ts.getOriginalNodeId(node)] = alias; } ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); @@ -47021,12 +46691,13 @@ var ts; var ts; (function (ts) { function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var enabledSubstitutions; var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; @@ -47061,6 +46732,82 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209: + return visitVariableStatementInAsyncBody(node); + case 215: + return visitForStatementInAsyncBody(node); + case 216: + return visitForInStatementInAsyncBody(node); + case 217: + return visitForOfStatementInAsyncBody(node); + case 264: + return visitCatchClauseInAsyncBody(node); + case 208: + case 222: + case 236: + case 261: + case 262: + case 225: + case 213: + case 214: + case 212: + case 221: + case 223: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } function visitAwaitExpression(node) { return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } @@ -47084,6 +46831,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -47091,10 +46905,17 @@ var ts; var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; var isArrowFunction = node.kind === 188; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); @@ -47108,27 +46929,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -47366,8 +47188,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -52749,6 +52571,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71); + context.enableSubstitution(266); context.enableSubstitution(195); context.enableSubstitution(193); context.enableSubstitution(194); @@ -53464,6 +53287,31 @@ var ts; if (hint === 1) { return substituteExpression(node); } + else if (hint === 4) { + return substituteUnspecified(node); + } + return node; + } + function substituteUnspecified(node) { + switch (node.kind) { + case 266: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), node); + } + } + } return node; } function substituteExpression(node) { @@ -54081,9 +53929,9 @@ var ts; setSourceFile(oldSource); } } - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -54092,7 +53940,7 @@ var ts; if ((emitFlags & 128) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256) === 0 && tokenPos >= 0) { @@ -54748,9 +54596,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 | - 16384 | - (shouldUseResolverType ? 8192 : 0); + var format = 4096 | 8 | 4 | + 2048 | + (shouldUseResolverType ? 131072 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -54763,7 +54611,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 16384, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); errorNameNode = undefined; } } @@ -54993,7 +54841,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 16384, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); write(";"); writeLine(); return tempVarName; @@ -56135,7 +55983,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -56160,7 +56008,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); @@ -56170,7 +56017,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -56179,7 +56029,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -56293,7 +56146,7 @@ var ts; } ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -56353,14 +56206,27 @@ var ts; var generatedNames; var tempFlagsStack; var tempFlags; + var reservedNamesStack; + var reservedNames; var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -56383,6 +56249,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -56398,6 +56268,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -56425,7 +56305,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -56451,6 +56331,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0; + reservedNamesStack = []; comments.reset(); setWriter(undefined); } @@ -56512,13 +56393,15 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -56738,7 +56621,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -56759,7 +56642,7 @@ var ts; case 101: case 99: case 91: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; case 178: return emitArrayLiteralExpression(node); @@ -56842,19 +56725,20 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + writeStringLiteral(text); } } function emitIdentifier(node) { - write(getTextOfNode(node, false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, false), node.symbol); + emitList(node, node.typeArguments, 26896); } function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -56866,51 +56750,61 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -56919,8 +56813,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -56932,13 +56826,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 ? "get " : "set "); + writeKeyword(node.kind === 154 ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -56947,31 +56842,34 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -56981,7 +56879,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -57003,34 +56903,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; emitList(node, node.members, flags | 262144); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260); @@ -57039,29 +56944,29 @@ var ts; emitList(node, node.types, 264); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1) { - write(" "); + writeSpace(); } else { writeLine(); @@ -57069,42 +56974,47 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); } function emitObjectBindingPattern(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 262576); - write("}"); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - write("["); + writePunctuation("["); emitList(node, node.elements, 262448); - write("]"); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitArrayLiteralExpression(node) { var elements = node.elements; @@ -57138,7 +57048,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -57159,9 +57069,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -57169,26 +57079,27 @@ var ts; emitExpressionList(node, node.arguments, 1296); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -57201,30 +57112,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -57236,7 +57151,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26; @@ -57245,7 +57160,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, true); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -57273,12 +57188,12 @@ var ts; emitList(node, node.templateSpans, 131072); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -57291,17 +57206,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } function emitTemplateSpan(node) { @@ -57309,12 +57226,12 @@ var ts; emit(node.literal); } function emitBlock(node) { - writeToken(17, node.pos, node); + writeToken(17, node.pos, writePunctuation, node); emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18, node.statements.end, node); + writeToken(18, node.statements.end, writePunctuation, node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; @@ -57323,27 +57240,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90, node.pos, node); - write(" "); - writeToken(19, openParenPos, node); + var openParenPos = writeToken(90, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20, node.expression.end, node); + writeToken(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82, node.thenStatement.end, node); + writeToken(82, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -57352,55 +57269,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - writeToken(19, openParenPos, node); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - writeToken(19, openParenPos); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19, openParenPos); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -57414,58 +57339,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, contextNode); + pos = writeToken(token, pos, writer, contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96, node.pos, node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98, node.pos); - write(" "); - writeToken(19, openParenPos); + var openParenPos = writeToken(98, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20, node.expression.end); - write(" "); + writeToken(20, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -57473,21 +57402,23 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78, node.pos); - write(";"); + writeToken(78, node.pos, writeKeyword); + writeSemicolon(); } function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272); } function emitFunctionDeclaration(node) { @@ -57496,9 +57427,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -57528,19 +57459,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { if (ts.getEmitFlags(body) & 1) { @@ -57567,7 +57498,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -57579,7 +57511,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18, body.statements.end, body); + writeToken(18, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, true); @@ -57603,17 +57535,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -57621,66 +57557,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512) { - write(node.flags & 16 ? "namespace " : "module "); + writeKeyword(node.flags & 16 ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17, node.pos); + writeToken(17, node.pos, writePunctuation); emitList(node, node.clauses, 65); - writeToken(18, node.clauses.end); + writeToken(18, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71) { @@ -57692,23 +57639,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -57718,28 +57672,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -57748,21 +57718,24 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitJsxElement(node) { emit(node.openingElement); @@ -57770,13 +57743,13 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -57784,44 +57757,45 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -57833,13 +57807,15 @@ var ts; } } function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -57852,31 +57828,32 @@ var ts; } var format = 81985; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 | 64); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272); } function emitCatchClause(node) { - var openParenPos = writeToken(74, node.pos); - write(" "); + var openParenPos = writeToken(74, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19, openParenPos); + writeToken(19, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration.end); - write(" "); + writeToken(20, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); var initializer = node.initializer; if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512) === 0) { var commentRange = ts.getCommentRange(initializer); @@ -57887,19 +57864,21 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitSourceFile(node) { writeLine(); @@ -57982,33 +57961,60 @@ var ts; } } } + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328); - write(" "); + writeSpace(); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); - } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); - } - function emitNodeWithPrefix(prefix, node, emit) { + function emitTypeAnnotation(node) { if (node) { - write(prefix); + writePunctuation(":"); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1) { - write(" "); + writeSpace(); emit(node); } else { @@ -58022,13 +58028,16 @@ var ts; emitList(parentNode, decorators, 24577); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960); + emitList(parentNode, typeArguments, 26896); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360); + emitList(parentNode, parameters, 1296); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -58048,7 +58057,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 & ~1024); + emitList(parentNode, parameters, 1296 & ~1024); } else { emitParameters(parentNode, parameters); @@ -58063,6 +58072,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28) { + case 0: + break; + case 16: + writePunctuation(","); + break; + case 4: + writeSpace(); + writePunctuation("|"); + break; + case 8: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -58081,7 +58107,7 @@ var ts; return; } if (format & 7680) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -58091,7 +58117,7 @@ var ts; writeLine(); } else if (format & 128 && !(format & 262144)) { - write(" "); + writeSpace(); } } else { @@ -58102,21 +58128,20 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128) { - write(" "); + writeSpace(); } if (format & 64) { increaseIndent(); } var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; if (previousSibling) { - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { if ((format & (3 | 64)) === 0) { increaseIndent(); @@ -58126,7 +58151,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256) { - write(" "); + writeSpace(); } } if (shouldEmitInterveningComments) { @@ -58147,9 +58172,9 @@ var ts; } var hasTrailingComma = (format & 32) && children.hasTrailingComma; if (format & 16 && hasTrailingComma) { - write(","); + writePunctuation(","); } - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { + if (previousSibling && format & 28 && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { emitLeadingCommentsOfPosition(previousSibling.end); } if (format & 64) { @@ -58159,50 +58184,102 @@ var ts; writeLine(); } else if (format & 128) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1) { - write(" "); + writeSpace(); } else { writeLine(); @@ -58385,16 +58462,24 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } function popNameGenerationScope(node) { if (node && ts.getEmitFlags(node) & 524288) { return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } function generateName(name) { - if (name.autoGenerateKind === 4) { - if (name.skipNameGenerationScope) { + if ((name.autoGenerateFlags & 7) === 4) { + if (name.autoGenerateFlags & 8) { var savedTempFlags = tempFlags; popNameGenerationScope(undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -58418,7 +58503,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { @@ -58431,11 +58517,14 @@ var ts; } return true; } - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -58447,6 +58536,9 @@ var ts; ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -58513,11 +58605,11 @@ var ts; } } function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7) { case 1: - return makeTempVariableName(0); + return makeTempVariableName(0, !!(name.autoGenerateFlags & 16)); case 2: - return makeTempVariableName(268435456); + return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 16)); case 3: return makeUniqueName(ts.idText(name)); } @@ -58530,7 +58622,7 @@ var ts; while (original) { node = original; if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 + && node.autoGenerateFlags === 4 && node.autoGenerateId !== autoGenerateId) { break; } @@ -58540,17 +58632,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0] = ""; - delimiters[16] = ","; - delimiters[4] = " |"; - delimiters[8] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28]; - } function createBracketsMap() { var brackets = []; brackets[512] = ["{", "}"]; @@ -58568,6 +58649,168 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + if (!host.directoryExists) { + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + clearCache(); + } + else { + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; var ConfigFileProgramReloadLevel; (function (ConfigFileProgramReloadLevel) { ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; @@ -58604,6 +58847,13 @@ var ts; } } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; function addFileWatcher(host, file, cb) { return host.watchFile(file, cb); } @@ -58679,346 +58929,6 @@ var ts; ts.closeFileWatcherOf = closeFileWatcherOf; })(ts || (ts = {})); var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - function createBuilder(options) { - var isModuleEmit; - var fileInfos = ts.createMap(); - var semanticDiagnosticsPerFile = ts.createMap(); - var changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - } - hasShapeChanged.clear(); - allFilesExcludingDefaultLibraryFile = undefined; - ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { - createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, - onDeleteValue: removeExistingFileInfo, - onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } - }); - } - function registerChangedFile(path) { - changedFilesSet.set(path, true); - semanticDiagnosticsPerFile.delete(path); - } - function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - function removeExistingFileInfo(_existingFileInfo, path) { - changedFilesSet.delete(path); - semanticDiagnosticsPerFile.delete(path); - emitHandler.onRemoveSourceFile(path); - } - function updateExistingFileInfo(program, existingInfo, sourceFile) { - if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - var compilerOptions = program.getCompilerOptions(); - if (!changedFilesSet.size) { - return ts.emptyArray; - } - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - changedFilesSet.clear(); - return [program.emit(undefined, writeFileCallback)]; - } - var seenFiles = ts.createMap(); - var result; - changedFilesSet.forEach(function (_true, path) { - var affectedFiles = getFilesAffectedBy(program, path); - affectedFiles.forEach(function (affectedFile) { - semanticDiagnosticsPerFile.delete(affectedFile.path); - if (!seenFiles.has(affectedFile.path)) { - seenFiles.set(affectedFile.path, true); - (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - ts.Debug.assert(changedFilesSet.size === 0); - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - return program.getSemanticDiagnostics(undefined, cancellationToken); - } - var diagnostics; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); - } - return diagnostics || ts.emptyArray; - } - function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - if (cachedDiagnostics) { - return cachedDiagnostics; - } - var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, diagnostics); - return diagnostics; - } - function clear() { - isModuleEmit = undefined; - emitHandler = undefined; - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - function updateShapeSignature(program, sourceFile) { - ts.Debug.assert(!!sourceFile); - if (hasShapeChanged.has(sourceFile.path)) { - return false; - } - hasShapeChanged.set(sourceFile.path, true); - var info = fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); - var prevSignature = info.signature; - var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { - if (allFilesExcludingDefaultLibraryFile) { - return allFilesExcludingDefaultLibraryFile; - } - var result; - addSourceFile(firstSourceFile); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - if (sourceFile !== firstSourceFile) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function getFilesAffectedByUpdatedShape(program, sourceFile) { - var options = program.getCompilerOptions(); - if (options && (options.out || options.outFile)) { - return [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.arrayFrom(ts.mapDefinedIterator(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - })); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return [sourceFile]; - } - var seenFileNamesMap = ts.createMap(); - var path = sourceFile.path; - seenFileNamesMap.set(path, sourceFile); - var queue = getReferencedByPaths(path); - while (queue.length > 0) { - var currentPath = queue.pop(); - if (!seenFileNamesMap.has(currentPath)) { - var currentSourceFile = program.getSourceFileByPath(currentPath); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); - } - } - } - ts.createBuilder = createBuilder; -})(ts || (ts = {})); -var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; function findConfigFile(searchPath, fileExists, configName) { @@ -59236,9 +59146,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = 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_5), lastLine = _b.line, lastLineChar = _b.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 hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -59500,7 +59410,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -59824,24 +59735,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -60331,7 +60244,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); @@ -60761,6 +60674,19 @@ var ts; hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + return ts.forEachEmittedFile(getEmitHost(), function (_a) { + var jsFilePath = _a.jsFilePath, declarationFilePath = _a.declarationFilePath; + return isSameFile(jsFilePath, file) || + (declarationFilePath && isSameFile(declarationFilePath, file)); + }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } } ts.createProgram = createProgram; function getResolutionDiagnostic(options, _a) { @@ -60801,9 +60727,522 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +(function (ts) { + var BuilderState; + (function (BuilderState) { + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + ts.Debug.assert(!!sourceFile); + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + function getAllDependencies(state, programOfThisState, sourceFile) { + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + 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) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + var seenFileNamesMap = ts.createMap(); + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + if (map1 === undefined) { + return map2 === undefined; + } + if (map2 === undefined) { + return map1 === undefined; + } + return map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + if (useOldState) { + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState && oldState.referencedMap; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + if (!useOldState || + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + oldInfo.version !== info.version || + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + } + } + }); + return state; + } + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var affectedFilesIndex = state.affectedFilesIndex; + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + state.affectedFilesIndex = affectedFilesIndex; + semanticDiagnosticsPerFile.delete(affectedFile.path); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + state.affectedFiles = undefined; + } + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + return undefined; + } + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + state.currentChangedFilePath = nextKey.value; + state.semanticDiagnosticsPerFile.delete(nextKey.value); + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + if (cachedDiagnostics) { + return cachedDiagnostics; + } + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var host; + var newProgram; + if (ts.isArray(newProgramOrRootNames)) { + newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram()); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram; + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program) { + newProgram = undefined; + oldState = undefined; + return oldProgram; + } + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + newProgram = undefined; + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + return undefined; + } + return toAffectedFileResult(state, state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + var sourceMaps = []; + var emitSkipped = void 0; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + return undefined; + } + else if (affected === state.program) { + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(undefined, cancellationToken), affected); + } + if (ignoreSourceFile && ignoreSourceFile(affected)) { + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + 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)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram).newProgram; + return { + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +var ts; (function (ts) { ts.maxNumberOfFilesToIterateForInvalidation = 256; - function createResolutionCache(resolutionHost, rootDirForResolution) { + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var allFilesHaveInvalidatedResolution = false; @@ -60812,6 +61251,7 @@ var ts; var resolvedTypeReferenceDirectives = ts.createMap(); var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); @@ -60861,8 +61301,8 @@ var ts; filesWithChangedSetOfUnresolvedImports = undefined; return collected; } - function createHasInvalidatedResolution() { - if (allFilesHaveInvalidatedResolution) { + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { filesWithInvalidatedResolutions = undefined; return ts.returnTrue; } @@ -60973,8 +61413,8 @@ var ts; function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, undefined, false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames, logChanges) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChanges); + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); @@ -61095,8 +61535,8 @@ var ts; function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } if (!allFilesHaveInvalidatedResolution && dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { @@ -61174,6 +61614,9 @@ var ts; if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { return false; } + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } } @@ -61188,8 +61631,8 @@ var ts; function createTypeRootsWatch(_typeRootPath, typeRoot) { return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } resolutionHost.onChangedAutomaticTypeDirectiveNames(); }, 1); @@ -61221,100 +61664,109 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var defaultFormatDiagnosticsHost = ts.sys ? { + var sysFormatDiagnosticsHost = ts.sys ? { getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, getNewLine: function () { return ts.sys.newLine; }, getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) } : undefined; - function createDiagnosticReporter(system, worker, formatDiagnosticsHost) { - if (system === void 0) { system = ts.sys; } - if (worker === void 0) { worker = reportDiagnosticSimply; } - return function (diagnostic) { return worker(diagnostic, getFormatDiagnosticsHost(), system); }; - function getFormatDiagnosticsHost() { - return formatDiagnosticsHost || (formatDiagnosticsHost = system === ts.sys ? defaultFormatDiagnosticsHost : { - getCurrentDirectory: function () { return system.getCurrentDirectory(); }, - getNewLine: function () { return system.newLine; }, - getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), - }); + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; + }; } ts.createDiagnosticReporter = createDiagnosticReporter; - function createWatchDiagnosticReporter(system) { - if (system === void 0) { system = ts.sys; } - return function (diagnostic) { - var output = new Date().toLocaleTimeString() + " - "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine + system.newLine); - system.write(output); - }; - } - ts.createWatchDiagnosticReporter = createWatchDiagnosticReporter; - function createWatchDiagnosticReporterWithColor(system) { - if (system === void 0) { system = ts.sys; } - return function (diagnostic) { - var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; - output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine + system.newLine); - system.write(output); - }; - } - ts.createWatchDiagnosticReporterWithColor = createWatchDiagnosticReporterWithColor; - function reportDiagnostics(diagnostics, reportDiagnostic) { - for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) { - var diagnostic = diagnostics_3[_i]; - reportDiagnostic(diagnostic); + function clearScreenIfNotWatchingForFileChanges(system, diagnostic) { + if (system.clearScreen && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + system.clearScreen(); } } - ts.reportDiagnostics = reportDiagnostics; - function reportDiagnosticSimply(diagnostic, host, system) { - system.write(ts.formatDiagnostic(diagnostic, host)); + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + }; } - ts.reportDiagnosticSimply = reportDiagnosticSimply; - function reportDiagnosticWithColorAndContext(diagnostic, host, system) { - system.write(ts.formatDiagnosticsWithColorAndContext([diagnostic], host) + host.getNewLine()); + ts.createWatchStatusReporter = createWatchStatusReporter; + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = parseConfigFile(configFileName, optionsToExtend, host); + host.onConfigFileDiagnostic = undefined; + host.onUnRecoverableConfigFileDiagnostic = undefined; + return result; } - ts.reportDiagnosticWithColorAndContext = reportDiagnosticWithColorAndContext; - function parseConfigFile(configFileName, optionsToExtend, system, reportDiagnostic, reportWatchDiagnostic) { + ts.parseConfigFileWithSystem = parseConfigFileWithSystem; + function parseConfigFile(configFileName, optionsToExtend, host) { var configFileText; try { - configFileText = system.readFile(configFileName); + configFileText = host.readFile(configFileName); } catch (e) { var error = ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, configFileName, e.message); - reportWatchDiagnostic(error); - system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - return; + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; } if (!configFileText) { var error = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName); - reportDiagnostics([error], reportDiagnostic); - system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); - return; + host.onUnRecoverableConfigFileDiagnostic(error); + return undefined; } var result = ts.parseJsonText(configFileName, configFileText); - reportDiagnostics(result.parseDiagnostics, reportDiagnostic); - var cwd = system.getCurrentDirectory(); - var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, system, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); - reportDiagnostics(configParseResult.errors, reportDiagnostic); + result.parseDiagnostics.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + var cwd = host.getCurrentDirectory(); + var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + configParseResult.errors.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); return configParseResult; } ts.parseConfigFile = parseConfigFile; - function reportEmittedFiles(files, system) { - if (!files || files.length === 0) { - return; + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName) { + var diagnostics = program.getSyntacticDiagnostics().slice(); + var reportSemanticDiagnostics = false; + if (diagnostics.length === 0) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === 0) { + reportSemanticDiagnostics = true; + } } - var currentDir = system.getCurrentDirectory(); - for (var _i = 0, files_2 = files; _i < files_2.length; _i++) { - var file = files_2[_i]; - var filepath = ts.getNormalizedAbsolutePath(file, currentDir); - system.write("TSFILE: " + filepath + system.newLine); + var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); } - } - function handleEmitOutputAndReportErrors(system, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic) { - reportDiagnostics(ts.sortAndDeduplicateDiagnostics(diagnostics), reportDiagnostic); - reportEmittedFiles(emittedFiles, system); - if (program.getCompilerOptions().listFiles) { - ts.forEach(program.getSourceFiles(), function (file) { - system.write(file.fileName + system.newLine); + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } } if (emitSkipped && diagnostics.length > 0) { return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; @@ -61324,89 +61776,90 @@ var ts; } return ts.ExitStatus.Success; } - ts.handleEmitOutputAndReportErrors = handleEmitOutputAndReportErrors; - function createWatchingSystemHost(pretty, system, parseConfigFile, reportDiagnostic, reportWatchDiagnostic) { + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { if (system === void 0) { system = ts.sys; } - reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system, pretty ? reportDiagnosticWithColorAndContext : reportDiagnosticSimply); - reportWatchDiagnostic = reportWatchDiagnostic || pretty ? createWatchDiagnosticReporterWithColor(system) : createWatchDiagnosticReporter(system); - parseConfigFile = parseConfigFile || ts.parseConfigFile; + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; return { - system: system, - parseConfigFile: parseConfigFile, - reportDiagnostic: reportDiagnostic, - reportWatchDiagnostic: reportWatchDiagnostic, - beforeCompile: ts.noop, - afterCompile: compileWatchedProgram, + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + 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 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); }, + onWatchStatusChange: reportWatchStatus || createWatchStatusReporter(system), + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder }; - function compileWatchedProgram(host, program, builder) { - var diagnostics = program.getSyntacticDiagnostics().slice(); - var reportSemanticDiagnostics = false; - if (diagnostics.length === 0) { - ts.addRange(diagnostics, program.getOptionsDiagnostics()); - ts.addRange(diagnostics, program.getGlobalDiagnostics()); - if (diagnostics.length === 0) { - reportSemanticDiagnostics = true; - } - } - var emittedFiles = program.getCompilerOptions().listEmittedFiles ? [] : undefined; - var sourceMaps; - var emitSkipped; - var result = builder.emitChangedFiles(program, writeFile); - if (result.length === 0) { - emitSkipped = true; - } - else { - for (var _i = 0, result_4 = result; _i < result_4.length; _i++) { - var emitOutput = result_4[_i]; - if (emitOutput.emitSkipped) { - emitSkipped = true; - } - ts.addRange(diagnostics, emitOutput.diagnostics); - sourceMaps = ts.concatenate(sourceMaps, emitOutput.sourceMaps); - } - } - if (reportSemanticDiagnostics) { - ts.addRange(diagnostics, builder.getSemanticDiagnostics(program)); - } - return handleEmitOutputAndReportErrors(host, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic); - function ensureDirectoriesExist(directoryPath) { - if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { - var parentDirectory = ts.getDirectoryPath(directoryPath); - ensureDirectoriesExist(parentDirectory); - host.createDirectory(directoryPath); - } - } - function writeFile(fileName, text, writeByteOrderMark, onError) { - try { - ts.performance.mark("beforeIOWrite"); - ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); - host.writeFile(fileName, text, writeByteOrderMark); - ts.performance.mark("afterIOWrite"); - ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); - if (emittedFiles) { - emittedFiles.push(fileName); - } - } - catch (e) { - if (onError) { - onError(e.message); - } - } - } + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName); } } - ts.createWatchingSystemHost = createWatchingSystemHost; - function createWatchModeWithConfigFile(configParseResult, optionsToExtend, watchingHost) { - if (optionsToExtend === void 0) { optionsToExtend = {}; } - return createWatchMode(configParseResult.fileNames, configParseResult.options, watchingHost, configParseResult.options.configFilePath, configParseResult.configFileSpecs, configParseResult.wildcardDirectories, optionsToExtend); + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } - ts.createWatchModeWithConfigFile = createWatchModeWithConfigFile; - function createWatchModeWithoutConfigFile(rootFileNames, compilerOptions, watchingHost) { - return createWatchMode(rootFileNames, compilerOptions, watchingHost); + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; } - ts.createWatchModeWithoutConfigFile = createWatchModeWithoutConfigFile; - function createWatchMode(rootFileNames, compilerOptions, watchingHost, configFileName, configFileSpecs, configFileWildCardDirectories, optionsToExtendForConfigFile) { - var program; + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + function createWatchProgram(host) { + var builderProgram; var reloadLevel; var missingFilesMap; var watchedWildcardDirectories; @@ -61415,85 +61868,116 @@ var ts; var missingFilePathsRequestedForRelease; var hasChangedCompilerOptions = false; var hasChangedAutomaticTypeDirectiveNames = false; - var loggingEnabled = compilerOptions.diagnostics || compilerOptions.extendedDiagnostics; - var writeLog = loggingEnabled ? function (s) { system.write(s); system.write(system.newLine); } : ts.noop; + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, configFileSpecs = host.configFileSpecs, configFileWildCardDirectories = host.configFileWildCardDirectories; + var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onConfigFileDiagnostic: host.onConfigFileDiagnostic, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + }; + if (configFileName && !rootFileNames) { + parseConfigFile(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); + var writeLog = loggingEnabled ? trace : ts.noop; var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; - watchingHost = watchingHost || createWatchingSystemHost(compilerOptions.pretty); - var system = watchingHost.system, parseConfigFile = watchingHost.parseConfigFile, reportDiagnostic = watchingHost.reportDiagnostic, reportWatchDiagnostic = watchingHost.reportWatchDiagnostic, beforeCompile = watchingHost.beforeCompile, afterCompile = watchingHost.afterCompile; - var directoryStructureHost = configFileName ? ts.createCachedDirectoryStructureHost(system) : system; if (configFileName) { - watchFile(system, configFileName, scheduleProgramReload, writeLog); + watchFile(host, configFileName, scheduleProgramReload, writeLog); } - var getCurrentDirectory = ts.memoize(function () { return directoryStructureHost.getCurrentDirectory(); }); - var realpath = system.realpath && (function (path) { return system.realpath(path); }); - var getCachedDirectoryStructureHost = configFileName && (function () { return directoryStructureHost; }); - var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames); - var newLine = ts.getNewLineCharacter(compilerOptions, system); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var newLine = updateNewLine(); var compilerHost = { getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, getSourceFileByPath: getVersionedSourceFileByPath, - getDefaultLibLocation: getDefaultLibLocation, - getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, - writeFile: ts.notImplemented, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, getCurrentDirectory: getCurrentDirectory, - useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; }, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, getCanonicalFileName: getCanonicalFileName, getNewLine: function () { return newLine; }, fileExists: fileExists, - readFile: function (fileName) { return system.readFile(fileName); }, - trace: function (s) { return system.write(s + newLine); }, - directoryExists: function (directoryName) { return directoryStructureHost.directoryExists(directoryName); }, - getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; }, - getDirectories: function (path) { return directoryStructureHost.getDirectories(path); }, - realpath: realpath, - resolveTypeReferenceDirectives: function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }, - resolveModuleNames: function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, false); }, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), toPath: toPath, getCompilationSettings: function () { return compilerOptions; }, watchDirectoryOfFailedLookupLocation: watchDirectory, watchTypeRootsDirectory: watchDirectory, - getCachedDirectoryStructureHost: getCachedDirectoryStructureHost, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, onInvalidatedResolution: scheduleProgramUpdate, onChangedAutomaticTypeDirectiveNames: function () { hasChangedAutomaticTypeDirectiveNames = true; scheduleProgramUpdate(); }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, writeLog: writeLog }; var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? - ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, getCurrentDirectory())) : - getCurrentDirectory()); - var builder = ts.createBuilder({ getCanonicalFileName: getCanonicalFileName, computeHash: computeHash }); - clearHostScreen(); - reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode)); + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, false); + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : + (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : + (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); synchronizeProgram(); watchConfigFileWildCardDirectories(); - return function () { return program; }; + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } function synchronizeProgram() { writeLog("Synchronizing program"); + var program = getCurrentProgram(); if (hasChangedCompilerOptions) { - newLine = ts.getNewLineCharacter(compilerOptions, system); + newLine = updateNewLine(); if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { resolutionCache.clear(); } } - var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(); - if (ts.isProgramUptoDate(program, rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { - return; + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + return builderProgram; } - beforeCompile(compilerOptions); var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; hasChangedCompilerOptions = false; resolutionCache.startCachingPerDirectoryResolution(); compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; - program = ts.createProgram(rootFileNames, compilerOptions, compilerHost, program); + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram); resolutionCache.finishCachingPerDirectoryResolution(); - builder.updateProgram(program); - ts.updateMissingFilePathsWatch(program, missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); if (needsUpdateInTypeRootWatch) { resolutionCache.updateTypeRootsWatch(); } @@ -61506,11 +61990,22 @@ var ts; } missingFilePathsRequestedForRelease = undefined; } - afterCompile(directoryStructureHost, program, builder); - reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes)); + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + reportWatchDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes); + return builderProgram; + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); } function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); } function fileExists(fileName) { var path = toPath(fileName); @@ -61520,9 +62015,6 @@ var ts; } return directoryStructureHost.fileExists(fileName); } - function getDefaultLibLocation() { - return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); - } function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { var hostSourceFile = sourceFilesCache.get(path); if (ts.isString(hostSourceFile)) { @@ -61538,7 +62030,7 @@ var ts; hostSourceFile.sourceFile = sourceFile; sourceFile.version = hostSourceFile.version.toString(); if (!hostSourceFile.fileWatcher) { - hostSourceFile.fileWatcher = watchFilePath(system, fileName, onSourceFileChange, path, writeLog); + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); } } else { @@ -61549,9 +62041,9 @@ var ts; else { var fileWatcher = void 0; if (sourceFile) { - sourceFile.version = "0"; - fileWatcher = watchFilePath(system, fileName, onSourceFileChange, path, writeLog); - sourceFilesCache.set(path, { sourceFile: sourceFile, version: 0, fileWatcher: fileWatcher }); + sourceFile.version = "1"; + fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: 1, fileWatcher: fileWatcher }); } else { sourceFilesCache.set(path, "0"); @@ -61564,7 +62056,7 @@ var ts; var text; try { ts.performance.mark("beforeIORead"); - text = system.readFile(fileName, compilerOptions.charset); + text = host.readFile(fileName, compilerOptions.charset); ts.performance.mark("afterIORead"); ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); } @@ -61602,42 +62094,42 @@ var ts; } } } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine); + } + } function scheduleProgramUpdate() { - if (!system.setTimeout || !system.clearTimeout) { + if (!host.setTimeout || !host.clearTimeout) { return; } if (timerToUpdateProgram) { - system.clearTimeout(timerToUpdateProgram); + host.clearTimeout(timerToUpdateProgram); } - timerToUpdateProgram = system.setTimeout(updateProgram, 250); + timerToUpdateProgram = host.setTimeout(updateProgram, 250); } function scheduleProgramReload() { ts.Debug.assert(!!configFileName); reloadLevel = ts.ConfigFileProgramReloadLevel.Full; scheduleProgramUpdate(); } - function clearHostScreen() { - if (watchingHost.system.clearScreen) { - watchingHost.system.clearScreen(); - } - } function updateProgram() { - clearHostScreen(); timerToUpdateProgram = undefined; - reportWatchDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation)); + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); switch (reloadLevel) { case ts.ConfigFileProgramReloadLevel.Partial: return reloadFileNamesFromConfigFile(); case ts.ConfigFileProgramReloadLevel.Full: return reloadConfigFile(); default: - return synchronizeProgram(); + synchronizeProgram(); + return; } } function reloadFileNamesFromConfigFile() { - var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, directoryStructureHost); + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { - reportDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + host.onConfigFileDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); } rootFileNames = result.fileNames; synchronizeProgram(); @@ -61645,17 +62137,21 @@ var ts; function reloadConfigFile() { writeLog("Reloading config file: " + configFileName); reloadLevel = ts.ConfigFileProgramReloadLevel.None; - var cachedHost = directoryStructureHost; - cachedHost.clearCache(); - var configParseResult = parseConfigFile(configFileName, optionsToExtendForConfigFile, cachedHost, reportDiagnostic, reportWatchDiagnostic); - rootFileNames = configParseResult.fileNames; - compilerOptions = configParseResult.options; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); hasChangedCompilerOptions = true; - configFileSpecs = configParseResult.configFileSpecs; - configFileWildCardDirectories = configParseResult.wildcardDirectories; synchronizeProgram(); watchConfigFileWildCardDirectories(); } + function parseConfigFile() { + var configParseResult = ts.parseConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); + rootFileNames = configParseResult.fileNames; + compilerOptions = configParseResult.options; + configFileSpecs = configParseResult.configFileSpecs; + configFileWildCardDirectories = configParseResult.wildcardDirectories; + } function onSourceFileChange(fileName, eventKind, path) { updateCachedSystemWithFile(fileName, path, eventKind); var hostSourceFile = sourceFilesCache.get(path); @@ -61664,7 +62160,7 @@ var ts; resolutionCache.invalidateResolutionOfFile(path); if (!ts.isString(hostSourceFile)) { hostSourceFile.fileWatcher.close(); - sourceFilesCache.set(path, (hostSourceFile.version++).toString()); + sourceFilesCache.set(path, (++hostSourceFile.version).toString()); } } else { @@ -61679,15 +62175,15 @@ var ts; scheduleProgramUpdate(); } function updateCachedSystemWithFile(fileName, path, eventKind) { - if (configFileName) { - directoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); } } function watchDirectory(directory, cb, flags) { - return watchDirectoryWorker(system, directory, cb, flags, writeLog); + return watchDirectoryWorker(host, directory, cb, flags, writeLog); } function watchMissingFilePath(missingFilePath) { - return watchFilePath(system, missingFilePath, onMissingFileChange, missingFilePath, writeLog); + return watchFilePath(host, missingFilePath, onMissingFileChange, missingFilePath, writeLog); } function onMissingFileChange(fileName, eventKind, missingFilePath) { updateCachedSystemWithFile(fileName, missingFilePath, eventKind); @@ -61699,13 +62195,18 @@ var ts; } } function watchConfigFileWildCardDirectories() { - ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + if (configFileWildCardDirectories) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } } function watchWildcardDirectory(directory, flags) { return watchDirectory(directory, function (fileOrDirectory) { ts.Debug.assert(!!configFileName); var fileOrDirectoryPath = toPath(fileOrDirectory); - var result = directoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + var result = cachedDirectoryStructureHost && cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); var hostSourceFile = sourceFilesCache.get(fileOrDirectoryPath); if (hostSourceFile && !ts.isString(hostSourceFile) && (result ? result.fileExists : directoryStructureHost.fileExists(fileOrDirectory))) { hostSourceFile.version++; @@ -61723,10 +62224,29 @@ var ts; } }, flags); } - function computeHash(data) { - return system.createHash ? system.createHash(data) : data; + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } } } + ts.createWatchProgram = createWatchProgram; })(ts || (ts = {})); var ts; (function (ts) { @@ -61868,7 +62388,7 @@ var ts; }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -63512,10 +64032,10 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - var reportDiagnostic = ts.createDiagnosticReporter(ts.sys, ts.reportDiagnosticSimply); + var reportDiagnostic = ts.createDiagnosticReporter(ts.sys); function udpateReportDiagnostic(options) { if (options.pretty) { - reportDiagnostic = ts.createDiagnosticReporter(ts.sys, ts.reportDiagnosticWithColorAndContext); + reportDiagnostic = ts.createDiagnosticReporter(ts.sys, true); } } function padLeft(s, length) { @@ -63537,7 +64057,7 @@ var ts; ts.validateLocaleAndSetLanguage(commandLine.options.locale, ts.sys, commandLine.errors); } if (commandLine.errors.length > 0) { - ts.reportDiagnostics(commandLine.errors, reportDiagnostic); + commandLine.errors.forEach(reportDiagnostic); return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (commandLine.options.init) { @@ -63585,12 +64105,11 @@ var ts; } var commandLineOptions = commandLine.options; if (configFileName) { - var reportWatchDiagnostic = ts.createWatchDiagnosticReporter(); - var configParseResult = ts.parseConfigFile(configFileName, commandLineOptions, ts.sys, reportDiagnostic, reportWatchDiagnostic); + var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, ts.sys, reportDiagnostic); udpateReportDiagnostic(configParseResult.options); if (ts.isWatchSet(configParseResult.options)) { reportWatchModeWithoutSysSupport(); - ts.createWatchModeWithConfigFile(configParseResult, commandLineOptions, createWatchingSystemHost(reportWatchDiagnostic)); + createWatchOfConfigFile(configParseResult, commandLineOptions); } else { performCompilation(configParseResult.fileNames, configParseResult.options); @@ -63600,7 +64119,7 @@ var ts; udpateReportDiagnostic(commandLineOptions); if (ts.isWatchSet(commandLineOptions)) { reportWatchModeWithoutSysSupport(); - ts.createWatchModeWithoutConfigFile(commandLine.fileNames, commandLineOptions, createWatchingSystemHost()); + createWatchOfFilesAndCompilerOptions(commandLine.fileNames, commandLineOptions); } else { performCompilation(commandLine.fileNames, commandLineOptions); @@ -63618,32 +64137,38 @@ var ts; var compilerHost = ts.createCompilerHost(compilerOptions); enableStatistics(compilerOptions); var program = ts.createProgram(rootFileNames, compilerOptions, compilerHost); - var exitStatus = compileProgram(program); + var exitStatus = ts.emitFilesAndReportErrors(program, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }); reportStatistics(program); return ts.sys.exit(exitStatus); } - function createWatchingSystemHost(reportWatchDiagnostic) { - var watchingHost = ts.createWatchingSystemHost(undefined, ts.sys, ts.parseConfigFile, reportDiagnostic, reportWatchDiagnostic); - watchingHost.beforeCompile = enableStatistics; - var afterCompile = watchingHost.afterCompile; - watchingHost.afterCompile = function (host, program, builder) { - afterCompile(host, program, builder); - reportStatistics(program); + function updateWatchCompilationHost(watchCompilerHost) { + var compileUsingBuilder = watchCompilerHost.createProgram; + watchCompilerHost.createProgram = function (rootNames, options, host, oldProgram) { + enableStatistics(options); + return compileUsingBuilder(rootNames, options, host, oldProgram); + }; + var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; + watchCompilerHost.afterProgramCreate = function (builderProgram) { + emitFilesUsingBuilder(builderProgram); + reportStatistics(builderProgram.getProgram()); }; - return watchingHost; } - function compileProgram(program) { - var diagnostics; - diagnostics = program.getSyntacticDiagnostics().slice(); - if (diagnostics.length === 0) { - diagnostics = program.getOptionsDiagnostics().concat(program.getGlobalDiagnostics()); - if (diagnostics.length === 0) { - diagnostics = program.getSemanticDiagnostics().slice(); - } - } - var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; - ts.addRange(diagnostics, emitDiagnostics); - return ts.handleEmitOutputAndReportErrors(ts.sys, program, emittedFiles, emitSkipped, diagnostics, reportDiagnostic); + function createWatchStatusReporter(options) { + return ts.createWatchStatusReporter(ts.sys, !!options.pretty); + } + function createWatchOfConfigFile(configParseResult, optionsToExtend) { + var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, ts.sys, undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); + updateWatchCompilationHost(watchCompilerHost); + watchCompilerHost.rootFiles = configParseResult.fileNames; + watchCompilerHost.options = configParseResult.options; + watchCompilerHost.configFileSpecs = configParseResult.configFileSpecs; + watchCompilerHost.configFileWildCardDirectories = configParseResult.wildcardDirectories; + ts.createWatchProgram(watchCompilerHost); + } + function createWatchOfFilesAndCompilerOptions(rootFiles, options) { + var watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, ts.sys, undefined, reportDiagnostic, createWatchStatusReporter(options)); + updateWatchCompilationHost(watchCompilerHost); + ts.createWatchProgram(watchCompilerHost); } function enableStatistics(compilerOptions) { if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { diff --git a/lib/tsserver.js b/lib/tsserver.js index 3c4ca85f057..a1cfb09ddd8 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -437,14 +437,17 @@ var ts; RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed"; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + 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 = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); var TokenFlags; (function (TokenFlags) { TokenFlags[TokenFlags["None"] = 0] = "None"; @@ -508,44 +511,60 @@ var ts; NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + 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["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + 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 = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + 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"] = 9469295] = "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 = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); var SymbolAccessibility; (function (SymbolAccessibility) { @@ -796,11 +815,9 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; - InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -1060,6 +1077,8 @@ var ts; 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"; @@ -1069,20 +1088,22 @@ var ts; TransformFlags[TransformFlags["AssertES2015"] = 192] = "AssertES2015"; TransformFlags[TransformFlags["AssertGenerator"] = 768] = "AssertGenerator"; TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 3072] = "AssertDestructuringAssignment"; - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + 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"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + 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 = {})); @@ -1154,6 +1175,72 @@ var ts; 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"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "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"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "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 = {})); })(ts || (ts = {})); var ts; (function (ts) { @@ -1215,7 +1302,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.7"; - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1224,6 +1311,7 @@ var ts; ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -1349,6 +1437,9 @@ var ts; } ts.forEach = forEach; function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -2359,6 +2450,8 @@ var ts; ts.returnTrue = returnTrue; function identity(x) { return x; } ts.identity = identity; + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; function notImplemented() { throw new Error("Not implemented"); } @@ -2686,7 +2779,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47) + if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92) return 3; } if (path.lastIndexOf("file:///", 0) === 0) { @@ -3349,10 +3442,10 @@ var ts; } function Signature() { } function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0; this.modifierFlagsCache = 0; this.transformFlags = 0; @@ -3486,9 +3579,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; function matchPatternOrExact(patternStrings, candidate) { @@ -3585,170 +3676,16 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - clearCache(); - } - else { - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - clearCache(); - } - else { - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } - } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -3989,7 +3926,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -4103,7 +4040,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -4688,6 +4630,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -4947,7 +4890,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -5056,6 +4999,7 @@ var ts; Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), 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."), @@ -5165,7 +5109,6 @@ var ts; Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -5708,7 +5651,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -5722,6 +5667,30 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + function parseNodeModuleFromPath(path) { + path = ts.normalizePath(path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = removeExtensionAndIndex(path.slice(indexAfterPackageName + 1)); + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function removeExtensionAndIndex(path) { + var noExtension = ts.removeFileExtension(path); + return noExtension === "index" ? "" : ts.removeSuffix(noExtension, "/index"); + } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); } @@ -5800,13 +5769,18 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -5949,13 +5923,17 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -6018,7 +5996,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -6041,15 +6018,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return str += " "; }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -6061,10 +6047,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -6105,6 +6091,12 @@ var ts; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -7349,41 +7341,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 && node.body && node.body.kind === 234 && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -7512,6 +7493,29 @@ var ts; return getAssignmentTargetKind(node) !== 0; } ts.isAssignmentTarget = isAssignmentTarget; + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208: + case 209: + case 221: + case 212: + case 222: + case 236: + case 261: + case 262: + case 223: + case 215: + case 216: + case 217: + case 213: + case 214: + case 225: + case 264: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -8252,7 +8256,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -8802,14 +8818,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0: return carriageReturnLineFeed; case 1: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; function formatEnum(value, enumObject, isFlags) { @@ -9788,7 +9804,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192; + return node.kind === 190; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -10232,7 +10248,7 @@ var ts; } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { - return ts.isIdentifier(node) && node.autoGenerateKind > 0; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7) > 0; } ts.isGeneratedIdentifier = isGeneratedIdentifier; function isModifierKind(token) { @@ -12653,8 +12669,8 @@ var ts; case 177: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 161: @@ -17061,7 +17077,6 @@ var ts; return result; } scanner.scanRange(start + 3, length - 5, function () { - var advanceToken = true; var state = 1; var margin = undefined; var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; @@ -17088,7 +17103,6 @@ var ts; removeTrailingNewlines(comments); parseTag(indent); state = 0; - advanceToken = false; margin = undefined; indent++; } @@ -17133,13 +17147,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - t = nextJSDocToken(); - } - else { - advanceToken = true; - t = currentToken; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -17223,7 +17231,8 @@ var ts; if (!tag) { return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -17247,6 +17256,7 @@ var ts; indent = 0; break; case 57: + scanner.setTextPos(scanner.getTextPos() - 1); case 1: break loop; case 5: @@ -17276,7 +17286,7 @@ var ts; } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281, atToken.pos); @@ -17284,8 +17294,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -17543,33 +17552,43 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0; + break; case "arg": case "argument": case "param": - return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -17588,6 +17607,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -20006,6 +20033,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180: return computePropertyAccess(node, subtreeFlags); + case 181: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -20014,13 +20043,15 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3; } if (subtreeFlags & 524288 - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 | 268435456))) { transformFlags |= 192; + if (expression.transformFlags & 268435456) { + transformFlags |= 16384; + } } if (expression.kind === 91) { transformFlags |= 67108864; @@ -20029,19 +20060,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97: - return true; - case 180: - case 181: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97; - } - return false; + return transformFlags & ~940049729; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20052,7 +20071,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537396545; + return transformFlags & ~940049729; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20069,7 +20088,7 @@ var ts; transformFlags |= 32; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20092,7 +20111,7 @@ var ts; transformFlags |= 192 | 131072; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20125,7 +20144,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + return transformFlags & ~942011713; } function computeClassExpression(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -20137,7 +20156,7 @@ var ts; transformFlags |= 16384; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~539358529; + return transformFlags & ~942011713; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20153,7 +20172,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20164,7 +20183,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~537920833; + return transformFlags & ~940574017; } function computeExpressionWithTypeArguments(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -20172,7 +20191,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20184,7 +20203,7 @@ var ts; transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computeMethod(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -20206,7 +20225,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20221,7 +20240,7 @@ var ts; transformFlags |= 8; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601015617; + return transformFlags & ~1003668801; } function computePropertyDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags | 3; @@ -20229,7 +20248,7 @@ var ts; transformFlags |= 8192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -20259,7 +20278,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + return transformFlags & ~1003935041; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20281,7 +20300,7 @@ var ts; transformFlags |= 768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601281857; + return transformFlags & ~1003935041; } function computeArrowFunction(node, subtreeFlags) { var transformFlags = subtreeFlags | 192; @@ -20300,17 +20319,27 @@ var ts; transformFlags |= 32768; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~601249089; + return transformFlags & ~1003902273; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; - if (expressionKind === 97) { - transformFlags |= 16384; + if (transformFlags & 134217728) { + transformFlags ^= 134217728; + transformFlags |= 268435456; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~671089985; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; + if (expressionFlags & 134217728) { + transformFlags &= ~134217728; + transformFlags |= 268435456; + } + node.transformFlags = transformFlags | 536870912; + return transformFlags & ~671089985; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20322,7 +20351,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -20337,7 +20366,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20346,7 +20375,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20354,7 +20383,7 @@ var ts; transformFlags |= 3; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -20362,7 +20391,7 @@ var ts; transformFlags |= 192; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~536872257; + return transformFlags & ~939525441; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3; @@ -20371,7 +20400,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~574674241; + return transformFlags & ~977327425; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432; @@ -20382,16 +20411,22 @@ var ts; transformFlags |= 192 | 4194304; } node.transformFlags = transformFlags | 536870912; - return transformFlags & ~546309441; + return transformFlags & ~948962625; } function computeOther(node, kind, subtreeFlags) { var transformFlags = subtreeFlags; - var excludeFlags = 536872257; + var excludeFlags = 939525441; switch (kind) { case 120: case 192: transformFlags |= 8 | 16; break; + case 185: + case 203: + case 292: + transformFlags |= 3; + excludeFlags = 536872257; + break; case 114: case 112: case 113: @@ -20400,8 +20435,6 @@ var ts; case 76: case 233: case 268: - case 185: - case 203: case 204: case 131: transformFlags |= 3; @@ -20499,7 +20532,8 @@ var ts; transformFlags |= 8 | 1048576; break; case 97: - transformFlags |= 192; + transformFlags |= 192 | 134217728; + excludeFlags = 536872257; break; case 99: transformFlags |= 16384; @@ -20509,11 +20543,11 @@ var ts; if (subtreeFlags & 524288) { transformFlags |= 8 | 1048576; } - excludeFlags = 537396545; + excludeFlags = 940049729; break; case 176: transformFlags |= 192 | 8388608; - excludeFlags = 537396545; + excludeFlags = 940049729; break; case 177: transformFlags |= 192; @@ -20525,7 +20559,7 @@ var ts; transformFlags |= 3 | 4096; break; case 179: - excludeFlags = 540087617; + excludeFlags = 942740801; if (subtreeFlags & 2097152) { transformFlags |= 192; } @@ -20538,7 +20572,7 @@ var ts; break; case 178: case 183: - excludeFlags = 537396545; + excludeFlags = 940049729; if (subtreeFlags & 524288) { transformFlags |= 192; } @@ -20573,27 +20607,27 @@ var ts; case 182: case 183: case 178: - return 537396545; + return 940049729; case 234: - return 574674241; + return 977327425; case 147: - return 536872257; + return 939525441; case 188: - return 601249089; + return 1003902273; case 187: case 229: - return 601281857; + return 1003935041; case 228: - return 546309441; + return 948962625; case 230: case 200: - return 539358529; + return 942011713; case 153: - return 601015617; + return 1003668801; case 152: case 154: case 155: - return 601015617; + return 1003668801; case 119: case 133: case 130: @@ -20612,14 +20646,23 @@ var ts; case 232: return -3; case 179: - return 540087617; + return 942740801; case 264: - return 537920833; + return 940574017; case 175: case 176: - return 537396545; - default: + return 940049729; + case 185: + case 203: + case 292: + case 186: + case 97: return 536872257; + case 180: + case 181: + return 671089985; + default: + return 939525441; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -20887,6 +20930,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -20920,10 +20968,25 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { @@ -21018,7 +21081,12 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -21225,13 +21293,13 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - var _displayBuilder; 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) { @@ -21268,6 +21336,139 @@ var ts; var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 | 8192, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 | 3112960 | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -21283,8 +21484,10 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { - getDiagnostics(sourceFile, cancellationToken); + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -22293,7 +22496,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -22660,6 +22863,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064, false); return access.accessibility === 0; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455, false); + return access.accessibility === 0; + } function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) { if (symbol && enclosingDeclaration && !(symbol.flags & 262144)) { var initialSymbol = symbol; @@ -22750,97 +22957,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4; } + var nodeFlags = 3112960; + if (flags & 2) { + nodeFlags |= 128; + } + if (flags & 1) { + nodeFlags |= 512; + } + var builder = flags & 4 ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, entity, sourceFile, writer); + return writer; + } } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144) { + sigOutput = kind === 1 ? 162 : 161; + } + else { + sigOutput = kind === 1 ? 157 : 156; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, sig, sourceFile, writer); + return writer; + } } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); - } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4, typeNode, sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608; + context.flags &= ~8388608; if (!type) { context.encounteredError = true; return undefined; @@ -22877,6 +23118,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024) { + if (!(context.flags & 1048576)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140, ts.createKeywordTypeNode(137)); } if (type.flags & 2048) { @@ -22898,10 +23144,13 @@ var ts; return ts.createKeywordTypeNode(134); } if (type.flags & 32768 && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304) { + if (!context.encounteredError && !(context.flags & 32768)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -22914,7 +23163,7 @@ var ts; var name = type.symbol ? symbolToName(type.symbol, context, 793064, false) : ts.createIdentifier("?"); return ts.createTypeReferenceNode(name, undefined); } - if (!inTypeAlias && type.aliasSymbol && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + 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); @@ -22927,7 +23176,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144)) { context.encounteredError = true; } return undefined; @@ -22952,7 +23201,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1); @@ -22960,7 +23209,7 @@ var ts; function createAnonymousTypeNode(type) { var symbol = type.symbol; if (symbol) { - if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 && context.flags & 2048) || symbol.flags & (384 | 512) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455); @@ -22979,10 +23228,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + 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; + } } } else { @@ -22997,7 +23252,8 @@ var ts; return declaration.parent.kind === 269 || declaration.parent.kind === 235; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return ts.contains(context.symbolStack, symbol); + return (!!(context.flags & 4096) || ts.contains(context.symbolStack, symbol)) && + (!(context.flags & 8) || isValueSymbolAccessible(symbol, context.enclosingDeclaration)); } } } @@ -23022,11 +23278,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024) ? 0 : 1); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, false); @@ -23039,7 +23295,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -23053,12 +23309,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -23148,9 +23409,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + if (context.flags & 2048) { + if (propertySymbol.flags & 4194304) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 | 16) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } var propertyType = ts.getCheckFlags(propertySymbol) & 2048 ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455); + } + } var propertyName = symbolToName(propertySymbol, context, 107455, true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 ? ts.createToken(55) : undefined; @@ -23191,11 +23467,21 @@ var ts; var name = ts.getNameFromIndexInfo(indexInfo) || "x"; var indexerTypeNode = ts.createKeywordTypeNode(kind === 0 ? 136 : 133); var indexingParameter = ts.createParameter(undefined, undefined, undefined, name, undefined, indexerTypeNode, undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152)) { + context.encounteredError = true; + } return ts.createIndexSignature(undefined, indexInfo.isReadonly ? [ts.createToken(131)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); @@ -23214,7 +23500,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256) { if (returnTypeNode && returnTypeNode.kind === 119) { returnTypeNode = undefined; } @@ -23222,14 +23508,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + var savedContextFlags = context.flags; + context.flags &= ~512; var name = symbolToName(type.symbol, context, 793064, true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -23240,7 +23529,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -23264,45 +23553,20 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); var chain; var isTypeParameter = symbol.flags & 262144; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64)) { chain = getSymbolChain(symbol, meaning, true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 | 64 | 524288)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -23325,11 +23589,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 | 64 | 524288)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 | 512)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4, predicate, sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -23385,6 +23731,9 @@ var ts; return type.flags & 32 ? '"' + ts.escapeString(type.value) + '"' : "" + type.value; } function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 && symbol.escapedName === "default") { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -23394,7 +23743,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072)) { context.encounteredError = true; } switch (declaration.kind) { @@ -23413,677 +23762,6 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" ? "default" : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91) { - writePunctuation(writer, 21); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91) { - writePunctuation(writer, 22); - } - } - else { - writePunctuation(writer, 23); - writer.writeSymbol(symbolName, symbol); - } - } - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - if (flags & 1) { - if (ts.getCheckFlags(symbol) & 1) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if (endOfChain || - !(!parentSymbol && ts.forEach(symbol.declarations, hasExternalModuleSymbol)) && - !(symbol.flags & (2048 | 4096))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - var isTypeParameter = symbol.flags & 262144; - var typeFormatFlag = 256 & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 | 16384); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024; - if (type.flags & 33585807) { - writer.writeKeyword(!(globalFlags & 32) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 && !(type.flags & 131072)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064, 0, nextFlags); - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 || type.flags & (272 | 32768)) { - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064, 0, nextFlags); - } - else if (!(flags & 1024) && type.aliasSymbol && - ((flags & 65536) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 | 32)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024) { - if (flags & 131072) { - writeKeyword(writer, 140); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137); - } - else if (type.flags & 96) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288) { - if (flags & 128) { - writePunctuation(writer, 19); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128); - if (flags & 128) { - writePunctuation(writer, 20); - } - } - else if (type.flags & 1048576) { - writeType(type.objectType, 128); - writePunctuation(writer, 21); - writeType(type.indexType, 0); - writePunctuation(writer, 22); - } - else { - writePunctuation(writer, 17); - writeSpace(writer); - writePunctuation(writer, 24); - writeSpace(writer); - writePunctuation(writer, 18); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 ? 0 : 128); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - if (symbol.flags & 32 || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064, 0, flags); - } - if (pos < end) { - writePunctuation(writer, 27); - writeType(typeArguments[pos], 512); - pos++; - while (pos < end) { - writePunctuation(writer, 26); - writeSpace(writer); - writeType(typeArguments[pos], 0); - pos++; - } - writePunctuation(writer, 29); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1)) { - writeType(typeArguments[0], 128 | 32768); - writePunctuation(writer, 21); - writePunctuation(writer, 22); - } - else if (type.target.objectFlags & 8) { - writePunctuation(writer, 21); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26); - writePunctuation(writer, 22); - } - else if (flags & 16384 && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200) { - writeAnonymousType(type, flags); - } - else { - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent); - if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128) { - writePunctuation(writer, 19); - } - if (type.flags & 131072) { - writeTypeList(formatUnionTypes(type.types), 49); - } - else { - writeTypeList(type.types, 48); - } - if (flags & 128) { - writePunctuation(writer, 20); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - if (symbol.flags & 32 && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 && flags & 16384) || - symbol.flags & (384 | 512)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064, 0, flags); - } - else { - writeKeyword(writer, 119); - } - } - else { - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 && type.symbol && type.symbol.flags & 32; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192) && - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16) && - (symbol.parent || - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 || declaration.parent.kind === 235; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - return !!(flags & 4) || - ts.contains(symbolStack, symbol); - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 103); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455, 0, typeFormatFlags); - if (typeFormatFlags & 32768) { - writePunctuation(writer, 20); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216) { - writePunctuation(writer, 55); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128) { - return true; - } - else if (flags & 512) { - var typeParameters = callSignature.target && (flags & 64) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17); - writePunctuation(writer, 18); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128) { - writePunctuation(writer, 19); - } - writeKeyword(writer, 94); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16, undefined, symbolStack); - if (flags & 128) { - writePunctuation(writer, 20); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - var stringIndexInfo = resolved.objectFlags & 2048 && resolved.stringIndexInfo ? - createIndexInfo(anyType, resolved.stringIndexInfo.isReadonly, resolved.stringIndexInfo.declaration) : - resolved.stringIndexInfo; - buildIndexSignatureDisplay(stringIndexInfo, writer, 0, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384) { - if (p.flags & 4194304) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 | 16)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = ts.getCheckFlags(p) & 2048 ? anyType : getTypeOfSymbol(p); - if (p.flags & (16 | 8192) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, undefined, symbolStack); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56); - writeSpace(writer); - writeType(t, globalFlags & 16384); - writePunctuation(writer, 25); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0); - writePunctuation(writer, 22); - if (type.declaration.questionToken) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0); - writePunctuation(writer, 25); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 || targetSymbol.flags & 64 || targetSymbol.flags & 524288) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55); - } - writePunctuation(writer, 56); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - if (bindingPattern.kind === 175) { - writePunctuation(writer, 17); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18); - } - else if (bindingPattern.kind === 176) { - writePunctuation(writer, 21); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26); - } - writePunctuation(writer, 22); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27); - var flags = 512; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26); - writeSpace(writer); - flags = 0; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99); - } - writeSpace(writer); - writeKeyword(writer, 126); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 && isTypeAny(returnType)) { - return; - } - if (flags & 16) { - writeSpace(writer); - writePunctuation(writer, 36); - } - else { - writePunctuation(writer, 56); - } - writeSpace(writer); - var typePredicate = getTypePredicateOfSignature(signature); - if (typePredicate) { - buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1) { - writeKeyword(writer, 94); - writeSpace(writer); - } - if (signature.target && (flags & 64)) { - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131); - writeSpace(writer); - } - writePunctuation(writer, 21); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56); - writeSpace(writer); - switch (kind) { - case 1: - writeKeyword(writer, 133); - break; - case 0: - writeKeyword(writer, 136); - break; - } - writePunctuation(writer, 22); - writePunctuation(writer, 56); - writeSpace(writer); - if (info.type) { - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - } - else { - writeKeyword(writer, 119); - } - writePunctuation(writer, 25); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } function isDeclarationVisible(node) { if (node) { var links = getNodeLinks(node); @@ -24195,8 +23873,8 @@ var ts; function pushTypeResolution(target, propertyName) { var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { resolutionResults[i] = false; } return false; @@ -24230,6 +23908,10 @@ var ts; if (propertyName === 3) { return target.resolvedReturnType; } + if (propertyName === 4) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } function popTypeResolution() { @@ -24335,7 +24017,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1) || getIndexTypeOfType(parentType, 0); @@ -25025,7 +24708,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); return type.resolvedBaseTypes = ts.emptyArray; } if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { @@ -25065,7 +24748,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 1)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, undefined, 2)); } } else { @@ -25469,18 +25152,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -25970,12 +25654,15 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0)) { + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -25994,29 +25681,30 @@ var ts; return getResolvedBaseConstraint(type) !== circularConstraintType; } function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216) { var types = t.types; @@ -26036,7 +25724,7 @@ var ts; return stringType; } if (t.flags & 1048576) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -26052,7 +25740,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -26401,7 +26089,7 @@ var ts; function maybeAddJsSyntheticRestParameter(declaration, parameters) { var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -26678,12 +26366,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -26748,7 +26436,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, undefined, 1); + var typeStr = typeToString(type, undefined, 2); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { return unknownType; @@ -27242,8 +26930,8 @@ var ts; function getUnionTypePredicate(signatures) { var first; var types = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var sig = signatures_3[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred) { continue; @@ -27500,33 +27188,51 @@ var ts; } return false; } - function getTransformedIndexedAccessType(type) { + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 && getTemplateTypeFromMappedType(type) === neverType; + } + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - if (objectType.flags & 262144 && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0)); - } - else { - regularTypes.push(t); + if (objectType.flags & 262144 && isGenericObjectType(objectType)) { + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + 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 getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { if (isGenericIndexType(indexType) || !(accessNode && accessNode.kind === 181) && isGenericObjectType(objectType)) { if (objectType.flags & 1) { @@ -28341,7 +28047,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 256)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), undefined, 64)); } enumRelation.set(id, false); return false; @@ -28468,8 +28174,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, undefined, 256); - targetType = typeToString(target, undefined, 256); + sourceType = typeToString(source, undefined, 64); + targetType = typeToString(target, undefined, 64); } if (!message) { if (relation === comparableRelation) { @@ -28923,8 +28629,11 @@ var ts; return result; } } - else if (target.flags & 1048576 && source.indexType === target.indexType) { + else if (target.flags & 1048576) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -29912,6 +29621,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -29922,6 +29632,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -29953,7 +29664,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -29997,7 +29708,9 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return inference.candidates ? getUnionType(inference.candidates, 2) : emptyObjectType; + return inference.candidates ? getUnionType(inference.candidates, 2) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -30016,6 +29729,7 @@ var ts; if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -30064,15 +29778,20 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - var p = priority | (source === implicitNeverType ? 16 : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4) && target.flags & 32768 && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -30094,15 +29813,15 @@ var ts; } } else if (source.flags & 524288 && target.flags & 524288) { - priority ^= 1; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2) && target.flags & 524288) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1; + contravariant = !contravariant; } else if (source.flags & 1048576 && target.flags & 1048576) { inferFromTypes(source.objectType, target.objectType); @@ -30124,7 +29843,7 @@ var ts; } if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2; + priority |= 1; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -30163,9 +29882,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -30195,7 +29914,7 @@ var ts; var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4; + priority |= 2; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -30313,10 +30032,16 @@ var ts; !hasPrimitiveConstraint(inference.typeParameter) && (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter)); var baseCandidates = widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) : candidates; - var unwidenedType = inference.priority & 1 ? getCommonSubtype(baseCandidates) : - context.flags & 1 || inference.priority & 8 ? getUnionType(baseCandidates, 2) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 || inference.priority & 4 ? + getUnionType(baseCandidates, 2) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + if (inferredType.flags & 16384 && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2) { inferredType = silentNeverType; @@ -30599,14 +30324,6 @@ var ts; return 8388607; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576) { - var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; - var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); - if (result !== baseConstraint) { - return result; - } - return type; - } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -31521,13 +31238,14 @@ var ts; var parent = node.parent; return parent.kind === 180 || parent.kind === 182 && parent.expression === node || - parent.kind === 181 && parent.expression === node; + parent.kind === 181 && parent.expression === node || + parent.kind === 204 || + parent.kind === 177 && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288); } - function getDeclaredOrApparentType(symbol, node) { - var type = getTypeOfSymbol(symbol); + function getApparentTypeForLocation(type, node) { if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } @@ -31592,7 +31310,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3)) { @@ -31785,6 +31503,14 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { if (container.kind === 187 && @@ -31815,10 +31541,6 @@ var ts; return type; } } - if (noImplicitThis) { - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -32352,7 +32074,7 @@ var ts; return node ? node.contextualMapper : identityMapper; } function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0); + var signatures = getSignaturesOfType(type, 0); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -32882,8 +32604,8 @@ var ts; } if (sourceAttributesType) { var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); var inferenceContext = createInferenceContext(signature, isJavascript ? 4 : 0); @@ -33393,7 +33115,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } if (node.kind !== 180 || assignmentKind === 1 || @@ -33607,7 +33329,7 @@ var ts; } function isValidMethodAccess(method, type) { var propType = getTypeOfFuncClassEnumModule(method); - var signatures = getSignaturesOfType(propType, 0); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { var thisType = getThisTypeOfSignature(sig); @@ -33755,8 +33477,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var signature = signatures_5[_i]; + 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 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -33866,7 +33588,7 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -33891,7 +33613,7 @@ var ts; getOrCreateTypeFromSignature(getSignatureInstantiation(contextualSignature, contextualSignature.typeParameters, ts.isInJavaScriptFile(node))) : instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4); } } var thisType = getThisTypeOfSignature(signature); @@ -34226,8 +33948,8 @@ var ts; else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -34237,8 +33959,8 @@ var ts; else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var sig = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -35395,6 +35117,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -36806,8 +36531,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_8 = signatures; _a < signatures_8.length; _a++) { - var signature = signatures_8[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -37703,7 +37428,13 @@ var ts; } if (ts.isBindingPattern(node.name)) { if (node.initializer && node.parent.parent.kind !== 216) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, undefined); + } checkParameterInitializer(node); } return; @@ -38289,7 +38020,7 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -40338,20 +40069,20 @@ var ts; : unknownType; if (type.flags & 1024 && type.symbol === symbol) { - flags |= 131072; + flags |= 1048576; } - if (flags & 8192) { + if (flags & 131072) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -41427,12 +41158,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 || node.name.kind === 175) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); } @@ -41838,7 +41572,7 @@ var ts; var node = createSynthesizedNode(71); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0; - node.autoGenerateKind = 0; + node.autoGenerateFlags = 0; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -41853,20 +41587,23 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1; + name.autoGenerateFlags = 1; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16; + } return name; } ts.createTempVariable = createTempVariable; function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2; + name.autoGenerateFlags = 2; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -41874,7 +41611,7 @@ var ts; ts.createLoopVariable = createLoopVariable; function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3; + name.autoGenerateFlags = 3; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -41882,10 +41619,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4; + name.autoGenerateFlags = 4; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8; + } nextAutoGenerateId++; return name; } @@ -42177,11 +41916,12 @@ var ts; : node; } ts.updateIndexSignature = updateIndexSignature; - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -44788,7 +44528,9 @@ var ts; } ts.parenthesizeForConditionalHead = parenthesizeForConditionalHead; function parenthesizeSubexpressionOfConditionalExpression(e) { - return e.kind === 195 && e.operatorToken.kind === 26 + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 && emittedExpression.operatorToken.kind === 26 || + emittedExpression.kind === 293 ? ts.createParen(e) : e; } @@ -45284,6 +45026,7 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -45393,7 +45136,7 @@ var ts; } switch (kind) { case 71: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145: @@ -46351,7 +46094,10 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + value = ensureIdentifier(flattenContext, value, false, location); + } + else if (needsValue) { value = ensureIdentifier(flattenContext, value, true, location); } else if (ts.nodeIsSynthesized(node)) { @@ -46381,6 +46127,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) { var pendingExpressions; var pendingDeclarations = []; @@ -46397,6 +46163,13 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + initializer = ensureIdentifier(flattenContext, initializer, false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(undefined); @@ -47067,10 +46840,13 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16; + classAliases[ts.getOriginalNodeId(node)] = alias; } ts.setEmitFlags(classExpression, 65536 | ts.getEmitFlags(classExpression)); expressions.push(ts.startOnNewLine(ts.createAssignment(temp, classExpression))); @@ -48367,12 +48143,13 @@ var ts; ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); var enabledSubstitutions; var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; context.onEmitNode = onEmitNode; @@ -48407,6 +48184,82 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209: + return visitVariableStatementInAsyncBody(node); + case 215: + return visitForStatementInAsyncBody(node); + case 216: + return visitForInStatementInAsyncBody(node); + case 217: + return visitForOfStatementInAsyncBody(node); + case 264: + return visitCatchClauseInAsyncBody(node); + case 208: + case 222: + case 236: + case 261: + case 262: + case 225: + case 213: + case 214: + case 212: + case 221: + case 223: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } function visitAwaitExpression(node) { return ts.setOriginalNode(ts.setTextRange(ts.createYield(undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node); } @@ -48430,6 +48283,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -48437,10 +48357,17 @@ var ts; var promiseConstructor = languageVersion < 2 ? getPromiseConstructor(nodeType) : undefined; var isArrowFunction = node.kind === 188; var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192) !== 0; + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, true); ts.setTextRange(block, node.body); @@ -48454,27 +48381,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -48716,8 +48644,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -54213,6 +54141,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71); + context.enableSubstitution(266); context.enableSubstitution(195); context.enableSubstitution(193); context.enableSubstitution(194); @@ -54928,6 +54857,31 @@ var ts; if (hint === 1) { return substituteExpression(node); } + else if (hint === 4) { + return substituteUnspecified(node); + } + return node; + } + function substituteUnspecified(node) { + switch (node.kind) { + case 266: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), node); + } + } + } return node; } function substituteExpression(node) { @@ -55611,9 +55565,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 | - 16384 | - (shouldUseResolverType ? 8192 : 0); + var format = 4096 | 8 | 4 | + 2048 | + (shouldUseResolverType ? 131072 : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -55626,7 +55580,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 | 16384, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); errorNameNode = undefined; } } @@ -55856,7 +55810,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 | 16384, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 | 8 | 2048 | 4, writer); write(";"); writeLine(); return tempVarName; @@ -56998,7 +56952,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -57220,9 +57174,9 @@ var ts; setSourceFile(oldSource); } } - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -57231,7 +57185,7 @@ var ts; if ((emitFlags & 128) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256) === 0 && tokenPos >= 0) { @@ -57636,7 +57590,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, emitOnlyDtsFiles) { var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile); @@ -57646,7 +57599,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -57655,7 +57611,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -57769,7 +57728,7 @@ var ts; } ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -57829,14 +57788,27 @@ var ts; var generatedNames; var tempFlagsStack; var tempFlags; + var reservedNamesStack; + var reservedNames; var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -57859,6 +57831,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -57874,6 +57850,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -57901,7 +57887,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -57927,6 +57913,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0; + reservedNamesStack = []; comments.reset(); setWriter(undefined); } @@ -57988,13 +57975,15 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { var kind = node.kind; if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -58214,7 +58203,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -58235,7 +58224,7 @@ var ts; case 101: case 99: case 91: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; case 178: return emitArrayLiteralExpression(node); @@ -58318,19 +58307,20 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + writeStringLiteral(text); } } function emitIdentifier(node) { - write(getTextOfNode(node, false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, false), node.symbol); + emitList(node, node.typeArguments, 26896); } function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -58342,51 +58332,61 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -58395,8 +58395,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -58408,13 +58408,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 ? "get " : "set "); + writeKeyword(node.kind === 154 ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -58423,31 +58424,34 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -58457,7 +58461,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -58479,34 +58485,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 ? 448 : 65; emitList(node, node.members, flags | 262144); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260); @@ -58515,29 +58526,29 @@ var ts; emitList(node, node.types, 264); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1) { - write(" "); + writeSpace(); } else { writeLine(); @@ -58545,42 +58556,47 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); } function emitObjectBindingPattern(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 262576); - write("}"); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - write("["); + writePunctuation("["); emitList(node, node.elements, 262448); - write("]"); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitArrayLiteralExpression(node) { var elements = node.elements; @@ -58614,7 +58630,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -58635,9 +58651,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -58645,26 +58661,27 @@ var ts; emitExpressionList(node, node.arguments, 1296); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -58677,30 +58694,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -58712,7 +58733,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26; @@ -58721,7 +58742,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, true); increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -58749,12 +58770,12 @@ var ts; emitList(node, node.templateSpans, 131072); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -58767,17 +58788,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } function emitTemplateSpan(node) { @@ -58785,12 +58808,12 @@ var ts; emit(node.literal); } function emitBlock(node) { - writeToken(17, node.pos, node); + writeToken(17, node.pos, writePunctuation, node); emitBlockStatements(node, !node.multiLine && isEmptyBlock(node)); increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18, node.statements.end, node); + writeToken(18, node.statements.end, writePunctuation, node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 ? 384 : 65; @@ -58799,27 +58822,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90, node.pos, node); - write(" "); - writeToken(19, openParenPos, node); + var openParenPos = writeToken(90, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20, node.expression.end, node); + writeToken(20, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82, node.thenStatement.end, node); + writeToken(82, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -58828,55 +58851,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - writeToken(19, openParenPos, node); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation, node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - writeToken(19, openParenPos); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19, openParenPos); + var openParenPos = writeToken(88, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20, node.expression.end); + writeToken(20, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -58890,58 +58921,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, contextNode); + pos = writeToken(token, pos, writer, contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96, node.pos, node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96, node.pos, writeKeyword, node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98, node.pos); - write(" "); - writeToken(19, openParenPos); + var openParenPos = writeToken(98, node.pos, writeKeyword); + writeSpace(); + writeToken(19, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20, node.expression.end); - write(" "); + writeToken(20, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -58949,21 +58984,23 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78, node.pos); - write(";"); + writeToken(78, node.pos, writeKeyword); + writeSemicolon(); } function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272); } function emitFunctionDeclaration(node) { @@ -58972,9 +59009,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -59004,19 +59041,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { if (ts.getEmitFlags(body) & 1) { @@ -59043,7 +59080,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -59055,7 +59093,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18, body.statements.end, body); + writeToken(18, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, true); @@ -59079,17 +59117,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -59097,66 +59139,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512) { - write(node.flags & 16 ? "namespace " : "module "); + writeKeyword(node.flags & 16 ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17, node.pos); + writeToken(17, node.pos, writePunctuation); emitList(node, node.clauses, 65); - writeToken(18, node.clauses.end); + writeToken(18, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71) { @@ -59168,23 +59221,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -59194,28 +59254,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -59224,21 +59300,24 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitJsxElement(node) { emit(node.openingElement); @@ -59246,13 +59325,13 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -59260,44 +59339,45 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -59309,13 +59389,15 @@ var ts; } } function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -59328,31 +59410,32 @@ var ts; } var format = 81985; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 | 64); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272); } function emitCatchClause(node) { - var openParenPos = writeToken(74, node.pos); - write(" "); + var openParenPos = writeToken(74, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19, openParenPos); + writeToken(19, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20, node.variableDeclaration.end); - write(" "); + writeToken(20, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); var initializer = node.initializer; if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512) === 0) { var commentRange = ts.getCommentRange(initializer); @@ -59363,19 +59446,21 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitSourceFile(node) { writeLine(); @@ -59458,33 +59543,60 @@ var ts; } } } + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328); - write(" "); + writeSpace(); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); - } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); - } - function emitNodeWithPrefix(prefix, node, emit) { + function emitTypeAnnotation(node) { if (node) { - write(prefix); + writePunctuation(":"); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1) { - write(" "); + writeSpace(); emit(node); } else { @@ -59498,13 +59610,16 @@ var ts; emitList(parentNode, decorators, 24577); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960); + emitList(parentNode, typeArguments, 26896); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360); + emitList(parentNode, parameters, 1296); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -59524,7 +59639,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 & ~1024); + emitList(parentNode, parameters, 1296 & ~1024); } else { emitParameters(parentNode, parameters); @@ -59539,6 +59654,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28) { + case 0: + break; + case 16: + writePunctuation(","); + break; + case 4: + writeSpace(); + writePunctuation("|"); + break; + case 8: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -59557,7 +59689,7 @@ var ts; return; } if (format & 7680) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -59567,7 +59699,7 @@ var ts; writeLine(); } else if (format & 128 && !(format & 262144)) { - write(" "); + writeSpace(); } } else { @@ -59578,21 +59710,20 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128) { - write(" "); + writeSpace(); } if (format & 64) { increaseIndent(); } var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; if (previousSibling) { - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { if ((format & (3 | 64)) === 0) { increaseIndent(); @@ -59602,7 +59733,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256) { - write(" "); + writeSpace(); } } if (shouldEmitInterveningComments) { @@ -59623,9 +59754,9 @@ var ts; } var hasTrailingComma = (format & 32) && children.hasTrailingComma; if (format & 16 && hasTrailingComma) { - write(","); + writePunctuation(","); } - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { + if (previousSibling && format & 28 && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024)) { emitLeadingCommentsOfPosition(previousSibling.end); } if (format & 64) { @@ -59635,50 +59766,102 @@ var ts; writeLine(); } else if (format & 128) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1) { - write(" "); + writeSpace(); } else { writeLine(); @@ -59861,16 +60044,24 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } function popNameGenerationScope(node) { if (node && ts.getEmitFlags(node) & 524288) { return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } function generateName(name) { - if (name.autoGenerateKind === 4) { - if (name.skipNameGenerationScope) { + if ((name.autoGenerateFlags & 7) === 4) { + if (name.autoGenerateFlags & 8) { var savedTempFlags = tempFlags; popNameGenerationScope(undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -59894,7 +60085,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } function isUniqueLocalName(name, container) { for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) { @@ -59907,11 +60099,14 @@ var ts; } return true; } - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -59923,6 +60118,9 @@ var ts; ? "_" + String.fromCharCode(97 + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -59989,11 +60187,11 @@ var ts; } } function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7) { case 1: - return makeTempVariableName(0); + return makeTempVariableName(0, !!(name.autoGenerateFlags & 16)); case 2: - return makeTempVariableName(268435456); + return makeTempVariableName(268435456, !!(name.autoGenerateFlags & 16)); case 3: return makeUniqueName(ts.idText(name)); } @@ -60006,7 +60204,7 @@ var ts; while (original) { node = original; if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 + && node.autoGenerateFlags === 4 && node.autoGenerateId !== autoGenerateId) { break; } @@ -60016,17 +60214,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0] = ""; - delimiters[16] = ","; - delimiters[4] = " |"; - delimiters[8] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28]; - } function createBracketsMap() { var brackets = []; brackets[512] = ["{", "}"]; @@ -60047,412 +60234,6 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - 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"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "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"] = 256] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "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"] = 26960] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat || (ListFormat = {})); -})(ts || (ts = {})); -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - function createBuilder(options) { - var isModuleEmit; - var fileInfos = ts.createMap(); - var semanticDiagnosticsPerFile = ts.createMap(); - var changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - } - hasShapeChanged.clear(); - allFilesExcludingDefaultLibraryFile = undefined; - ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { - createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, - onDeleteValue: removeExistingFileInfo, - onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } - }); - } - function registerChangedFile(path) { - changedFilesSet.set(path, true); - semanticDiagnosticsPerFile.delete(path); - } - function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - function removeExistingFileInfo(_existingFileInfo, path) { - changedFilesSet.delete(path); - semanticDiagnosticsPerFile.delete(path); - emitHandler.onRemoveSourceFile(path); - } - function updateExistingFileInfo(program, existingInfo, sourceFile) { - if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - var compilerOptions = program.getCompilerOptions(); - if (!changedFilesSet.size) { - return ts.emptyArray; - } - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - changedFilesSet.clear(); - return [program.emit(undefined, writeFileCallback)]; - } - var seenFiles = ts.createMap(); - var result; - changedFilesSet.forEach(function (_true, path) { - var affectedFiles = getFilesAffectedBy(program, path); - affectedFiles.forEach(function (affectedFile) { - semanticDiagnosticsPerFile.delete(affectedFile.path); - if (!seenFiles.has(affectedFile.path)) { - seenFiles.set(affectedFile.path, true); - (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - ts.Debug.assert(changedFilesSet.size === 0); - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - return program.getSemanticDiagnostics(undefined, cancellationToken); - } - var diagnostics; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); - } - return diagnostics || ts.emptyArray; - } - function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - if (cachedDiagnostics) { - return cachedDiagnostics; - } - var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, diagnostics); - return diagnostics; - } - function clear() { - isModuleEmit = undefined; - emitHandler = undefined; - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - function updateShapeSignature(program, sourceFile) { - ts.Debug.assert(!!sourceFile); - if (hasShapeChanged.has(sourceFile.path)) { - return false; - } - hasShapeChanged.set(sourceFile.path, true); - var info = fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); - var prevSignature = info.signature; - var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { - if (allFilesExcludingDefaultLibraryFile) { - return allFilesExcludingDefaultLibraryFile; - } - var result; - addSourceFile(firstSourceFile); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - if (sourceFile !== firstSourceFile) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function getFilesAffectedByUpdatedShape(program, sourceFile) { - var options = program.getCompilerOptions(); - if (options && (options.out || options.outFile)) { - return [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.arrayFrom(ts.mapDefinedIterator(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - })); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return [sourceFile]; - } - var seenFileNamesMap = ts.createMap(); - var path = sourceFile.path; - seenFileNamesMap.set(path, sourceFile); - var queue = getReferencedByPaths(path); - while (queue.length > 0) { - var currentPath = queue.pop(); - if (!seenFileNamesMap.has(currentPath)) { - var currentSourceFile = program.getSourceFileByPath(currentPath); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); - } - } - } - ts.createBuilder = createBuilder; })(ts || (ts = {})); var ts; (function (ts) { @@ -60672,9 +60453,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = 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_5), lastLine = _b.line, lastLineChar = _b.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 hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -60936,7 +60717,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -61265,24 +61047,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -61772,7 +61556,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path); @@ -62202,6 +61986,19 @@ var ts; hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + return ts.forEachEmittedFile(getEmitHost(), function (_a) { + var jsFilePath = _a.jsFilePath, declarationFilePath = _a.declarationFilePath; + return isSameFile(jsFilePath, file) || + (declarationFilePath && isSameFile(declarationFilePath, file)); + }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0; + } } ts.createProgram = createProgram; function getResolutionDiagnostic(options, _a) { @@ -62381,7 +62178,7 @@ var ts; }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -64874,8 +64671,8 @@ var ts; } } ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); @@ -65095,6 +64892,18 @@ var ts; return true; } ts.addToSeen = addToSeen; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; })(ts || (ts = {})); (function (ts) { function isFirstDeclarationOfSymbolParameter(symbol) { @@ -65107,6 +64916,7 @@ var ts; var lineStart; var indent; resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { displayParts: function () { return displayParts; }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, @@ -65116,8 +64926,18 @@ var ts; writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeSymbol: writeSymbol, writeLine: writeLine, + write: unknownWrite, + writeTextOfNode: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, @@ -65235,8 +65055,10 @@ var ts; } ts.textPart = textPart; var carriageReturnLineFeed = "\r\n"; - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; } ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; function lineBreakPart() { @@ -65255,20 +65077,20 @@ var ts; ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typechecker.writeType(type, enclosingDeclaration, flags | 1024, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - flags |= 65536; + flags |= 16384 | 1024 | 32 | 8192; return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + typechecker.writeSignature(signature, enclosingDeclaration, flags, undefined, writer); }); } ts.signatureToDisplayParts = signatureToDisplayParts; @@ -66024,7 +65846,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; if (lastEnd >= 0) { var whitespaceLength_1 = start - lastEnd; @@ -66032,8 +65854,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -66323,23 +66145,29 @@ var ts; if (!ts.isTrivia(kind)) { return start; } - if (kind === 4 || kind === 5) { - continue; - } - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - if (ch === 60 || ch === 62) { - pushClassification(start, width, 1); + switch (kind) { + case 4: + case 5: continue; - } - ts.Debug.assert(ch === 124 || ch === 61); - classifyDisabledMergeCode(text, start, end); + case 2: + case 3: + classifyComment(token, kind, start, width); + triviaScanner.setTextPos(end); + continue; + case 7: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + if (ch === 60 || ch === 62) { + pushClassification(start, width, 1); + continue; + } + ts.Debug.assert(ch === 124 || ch === 61); + classifyDisabledMergeCode(text, start, end); + break; + case 6: + break; + default: + ts.Debug.assertNever(kind); } } } @@ -66807,10 +66635,12 @@ var ts; PathCompletions.getTripleSlashReferenceCompletion = getTripleSlashReferenceCompletion; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } + var seen = ts.createMap(); if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, "external module name", span)); + var typesName = _a[_i]; + var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + pushResult(moduleName); } } else if (host.getDirectories) { @@ -66822,30 +66652,37 @@ var ts; if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(host, root, span, result); + getCompletionEntriesFromDirectories(root); } } - } - if (host.getDirectories) { for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, typesDir, span, result); + getCompletionEntriesFromDirectories(typesDir); } } return result; - } - function getCompletionEntriesFromDirectories(host, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name", span)); + function getCompletionEntriesFromDirectories(directory) { + ts.Debug.assert(!!host.getDirectories); + if (tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + var directoryName = ts.getBaseFileName(typeDirectory); + var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + pushResult(moduleName); + } } } } + function pushResult(moduleName) { + if (!seen.has(moduleName)) { + result.push(createCompletionEntryForModule(moduleName, "external module name", span)); + seen.set(moduleName, true); + } + } } function findPackageJsons(directory, host) { var paths = []; @@ -66966,16 +66803,19 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && pathCompletionsInfo(entries); } - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); - } var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteral(contextToken) && !ts.isNoSubstitutionTemplateLiteral(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host, log); + } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 || contextToken.kind === 77 || contextToken.kind === 71)) { return getLabelCompletionAtPosition(contextToken.parent); @@ -67062,22 +66902,28 @@ var ts; return undefined; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - ts.Debug.assert(!(needsConvertPropertyAccess && !propertyAccessToConvert)); if (needsConvertPropertyAccess && !includeInsertTextCompletions) { return undefined; } + var insertText; + var replacementSpan; + if (kind === 1 && origin && origin.type === "this-type") { + insertText = needsConvertPropertyAccess ? "this[\"" + name + "\"]" : "this." + name; + } + else if (needsConvertPropertyAccess) { + insertText = "[\"" + name + "\"]"; + replacementSpan = ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end); + } return { name: name, kind: ts.SymbolDisplay.getSymbolKind(typeChecker, symbol, location), kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - insertText: needsConvertPropertyAccess ? "[\"" + name + "\"]" : undefined, - replacementSpan: needsConvertPropertyAccess - ? ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end) - : undefined, - hasAction: trueOrUndefined(needsConvertPropertyAccess || origin !== undefined), + hasAction: trueOrUndefined(!!origin && origin.type === "export"), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, }; } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { @@ -67088,7 +66934,7 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && ts.stripQuotes(origin.moduleSymbol.name); + return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); @@ -67118,35 +66964,46 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } } - function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || !ts.isStringLiteral(node) && !ts.isNoSubstitutionTemplateLiteral(node)) { - return undefined; - } - if (node.parent.kind === 265 && - node.parent.parent.kind === 179 && - node.parent.name === node) { - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - var type = typeChecker.getTypeAtLocation(node.parent.expression); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); - } - else if (node.parent.kind === 239 || node.parent.kind === 245 - || ts.isRequireCall(node.parent, false) || ts.isImportCall(node.parent) - || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker); - return pathCompletionsInfo(entries); - } - else if (ts.isIndexedAccessTypeNode(node.parent.parent)) { - var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); - } - else { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, log) { + switch (node.parent.kind) { + case 174: + switch (node.parent.parent.kind) { + case 160: + return undefined; + case 172: + var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + default: + return undefined; + } + case 265: + if (node.parent.parent.kind === 179 && + node.parent.name === node) { + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); + } + return fromContextualType(); + case 181: { + var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + var type = typeChecker.getTypeAtLocation(expression); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + } + break; } + case 182: + case 183: + if (!ts.isRequireCall(node.parent, false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + return argumentInfo ? getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) : fromContextualType(); + } + case 239: + case 245: + case 249: + return pathCompletionsInfo(Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker)); + default: + return fromContextualType(); + } + function fromContextualType() { return getStringLiteralCompletionEntriesFromType(getContextualTypeFromParent(node, typeChecker), typeChecker); } } @@ -67270,7 +67127,7 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.isDefaultExport && symbol.escapedName === "default" + return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) : symbol.name; @@ -67320,7 +67177,7 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo + return symbolOriginInfo && symbolOriginInfo.type === "export" ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) : { codeActions: undefined, sourceDisplay: undefined }; } @@ -67334,7 +67191,6 @@ var ts; host: host, program: program, checker: checker, - newLineCharacter: host.getNewLine(), compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, @@ -67644,6 +67500,9 @@ var ts; keywordFilters = 2; return true; } + if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { + keywordFilters = 3; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { getGetClassLikeCompletionSymbols(classLikeContainer); return true; @@ -67674,6 +67533,16 @@ var ts; } var symbolMeanings = 793064 | 107455 | 1920 | 2097152; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + if (options.includeInsertTextCompletions && scopeNode.kind !== 269) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, true); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbols.push(symbol); + } + } + } if (options.includeExternalModuleExports) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } @@ -67750,7 +67619,7 @@ var ts; ts.codefix.forEachExternalModuleToImportFrom(typeChecker, sourceFile, allSourceFiles, function (moduleSymbol) { for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { var symbol = _a[_i]; - if (symbol.parent !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + if (typeChecker.getMergedSymbol(symbol.parent) !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } @@ -67758,10 +67627,10 @@ var ts; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - var origin = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; if (stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; } } }); @@ -68061,6 +67930,21 @@ var ts; } return undefined; } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + }); + return container && container; + } + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -68332,12 +68216,12 @@ var ts; return validIdentiferResult; switch (kind) { case 5: - case 1: case 3: return undefined; case 0: return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2: + case 1: return name.charCodeAt(0) === 32 ? undefined : { name: name, needsConvertPropertyAccess: true }; case 4: return validIdentiferResult; @@ -68360,6 +68244,8 @@ var ts; return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); case 2: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + case 3: + return getFilteredKeywordCompletions(isFunctionLikeBodyCompletionKeywordText); default: ts.Debug.assertNever(keywordFilter); } @@ -68412,6 +68298,24 @@ var ts; function isConstructorParameterCompletionKeywordText(text) { return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); } + function isFunctionLikeBodyCompletionKeyword(kind) { + switch (kind) { + case 114: + case 112: + case 113: + case 131: + case 123: + case 115: + case 117: + case 125: + case 135: + return false; + } + return true; + } + function isFunctionLikeBodyCompletionKeywordText(text) { + return isFunctionLikeBodyCompletionKeyword(ts.stringToToken(text)); + } function isEqualityOperatorKind(kind) { switch (kind) { case 34: @@ -69780,7 +69684,7 @@ var ts; return undefined; } function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifier(symbol, node, checker); + symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker); var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; var state = new State(sourceFiles, getSpecialSearchKind(node), checker, cancellationToken, searchMeaning, options, result); @@ -69817,7 +69721,7 @@ var ts; return 0; } } - function skipPastExportOrImportSpecifier(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { var parent = node.parent; if (ts.isExportSpecifier(parent)) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); @@ -69825,7 +69729,11 @@ var ts; if (ts.isImportSpecifier(parent) && parent.propertyName === node) { return checker.getImmediateAliasedSymbol(symbol); } - return symbol; + return ts.firstDefined(symbol.declarations, function (decl) { + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }) || symbol; } var SpecialSearchKind; (function (SpecialSearchKind) { @@ -70873,26 +70781,14 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); if (!type) { return undefined; } if (type.flags & 131072 && !(type.flags & 16)) { - var result_5 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(result_5, getDefinitionFromSymbol(typeChecker, t.symbol, node)); - } - }); - return result_5; + return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(typeChecker, type.symbol, node); + return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function getDefinitionAndBoundSpan(program, sourceFile, position) { @@ -70930,55 +70826,27 @@ var ts; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var result = []; - var declarations = symbol.getDeclarations(); var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isNewExpressionTarget(location) || location.kind === 123) { - if (symbol.flags & 32) { - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + function getConstructSignatureDefinition() { + if (ts.isNewExpressionTarget(node) || node.kind === 123 && symbol.flags & 32) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, true); } - return false; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, false, symbolKind, symbolName, containerName, result); - } - return false; + function getCallSignatureDefinition() { + return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, false) + : undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + function getSignatureDefinition(signatureDeclarations, selectConstructors) { if (!signatureDeclarations) { - return false; + return undefined; } - var declarations = []; - var definition; - for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { - var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 153 : isSignatureDeclaration(d)) { - declarations.push(d); - if (d.body) - definition = d; - } - } - if (declarations.length) { - result.push(createDefinitionInfo(definition || ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; - } - return false; + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + : undefined; } } function isSignatureDeclaration(node) { @@ -71109,18 +70977,29 @@ var ts; function getJsDocCommentsFromDeclarations(declarations) { var documentationComment = []; forEachUnique(declarations, function (declaration) { - ts.forEach(ts.getAllJSDocs(declaration), function (doc) { - if (doc.comment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(ts.textPart(doc.comment)); + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); } - }); + documentationComment.push(ts.textPart(comment)); + } }); return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 289: + return [declaration]; + case 288: + return [declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } function getJsDocTagsFromDeclarations(declarations) { var tags = []; forEachUnique(declarations, function (declaration) { @@ -71150,10 +71029,13 @@ var ts; return comment; } function withNode(node) { - return node.getText() + " " + comment; + return addComment(node.getText()); } function withList(list) { - return list.map(function (x) { return x.getText(); }) + " " + comment; + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; } } function forEachUnique(array, callback) { @@ -71480,8 +71362,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_6.config; + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.config; if (baseFileName === "package.json" && packageJson._requiredBy && ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) { continue; @@ -73441,6 +73323,7 @@ var ts; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, undefined, undefined); + var printer = ts.createPrinter({ removeComments: true }); var items = ts.map(candidates, function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; @@ -73456,14 +73339,20 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29)); var parameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); + var flags = 8192 | 3112960; + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + printer.writeList(1296, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); } else { isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); + printer.writeList(26896, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + } }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19)); @@ -73471,7 +73360,15 @@ var ts; suffixDisplayParts.push(ts.punctuationPart(20)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + typeChecker.writeTypePredicate(predicate, invocation, undefined, writer); + } + else { + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, undefined, writer); + } }); ts.addRange(suffixDisplayParts, returnTypeParts); return { @@ -73492,7 +73389,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 | 3112960); + printer.writeNode(4, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: parameter.name, @@ -73503,7 +73401,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation); + var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); + printer.writeNode(4, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: typeParameter.symbol.name, @@ -73629,6 +73528,7 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 && ts.isExpression(location); var type; + var printer; var documentationFromAlias; if (symbolKind !== "" || symbolFlags & 32 || symbolFlags & 2097152) { if (symbolKind === "getter" || symbolKind === "setter") { @@ -73689,14 +73589,14 @@ var ts; displayParts.push(ts.punctuationPart(56)); displayParts.push(ts.spacePart()); if (!(type.flags & 65536 && type.objectFlags & 16) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 1)); + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, undefined, 4 | 1)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94)); displayParts.push(ts.spacePart()); } - addSignatureDisplayParts(signature, allSignatures, 16); + addSignatureDisplayParts(signature, allSignatures, 262144); break; default: addSignatureDisplayParts(signature, allSignatures); @@ -73759,7 +73659,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608)); } if (symbolFlags & 384) { prefixNextMeaning(); @@ -73806,7 +73706,7 @@ var ts; else if (declaration.kind !== 156 && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32)); } else if (declaration.kind === 232) { addInPrefix(); @@ -73910,7 +73810,8 @@ var ts; displayParts.push(ts.spacePart()); if (type.symbol && type.symbol.flags & 262144) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -73962,6 +73863,12 @@ var ts; documentation = documentationFromAlias; } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); @@ -73983,7 +73890,7 @@ var ts; if (alias && symbolToDisplay === symbol) { symbolToDisplay = alias; } - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, undefined, 1 | 2); + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, undefined, 1 | 2 | 4); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { @@ -74013,7 +73920,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19)); @@ -74028,7 +73935,8 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(26896, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -75308,26 +75216,27 @@ var ts; return -1; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var indentation = inheritedIndentation; var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { - indentation = startLine === lastIndentedLine - ? indentationOnLastIndentedLine - : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; } - else if (indentation === -1) { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); + else if (inheritedIndentation === -1) { + if (node.kind === 19 && startLine === lastIndentedLine) { + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; } } - return { - indentation: indentation, - delta: delta - }; + else { + return { indentation: inheritedIndentation, delta: delta }; + } } function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { @@ -75356,64 +75265,52 @@ var ts; case 18: case 22: case 20: - return indentation + getEffectiveDelta(delta, container); + return indentation + getDelta(container); } return tokenIndentation !== -1 ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind, container) { - if (nodeStartLine !== line && node.decorators) { - if (kind === getFirstNonDecoratorTokenOfNode(node)) { - return indentation; - } - } - switch (kind) { - case 17: - case 18: - case 19: - case 20: - case 82: - case 106: - case 57: - return indentation; - case 41: - case 29: { - if (container.kind === 252 || - container.kind === 253 || - container.kind === 251) { - return indentation; - } - break; - } - case 21: - case 22: { - if (container.kind !== 173) { - return indentation; - } - break; - } - } - return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; + return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, - getDelta: function (child) { return getEffectiveDelta(delta, child); }, + getDelta: getDelta, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { - if (lineAdded) { - indentation += options.indentSize; - } - else { - indentation -= options.indentSize; - } - if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; - } - else { - delta = 0; - } + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; } } }; - function getEffectiveDelta(delta, child) { + function shouldAddDelta(line, kind, container) { + switch (kind) { + case 17: + case 18: + case 19: + case 20: + case 82: + case 106: + case 57: + return false; + case 41: + case 29: + switch (container.kind) { + case 252: + case 253: + case 251: + return false; + } + break; + case 21: + case 22: + if (container.kind !== 173) { + return false; + } + break; + } + return nodeStartLine !== line + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { return formatting.SmartIndenter.nodeWillIndentChild(node, child, true) ? delta : 0; } } @@ -75623,18 +75520,20 @@ var ts; var trimTrailingWhitespaces; var lineAction = 0; if (rule) { - applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.action & (2 | 8) && currentStartLine !== previousStartLine) { - lineAction = 2; - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(false); - } - } - else if (rule.action & 4 && currentStartLine === previousStartLine) { - lineAction = 1; - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(true); - } + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2: + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(false); + } + break; + case 1: + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(true); + } + break; + default: + ts.Debug.assert(lineAction === 0); } trimTrailingWhitespaces = !(rule.action & 8) && rule.flags !== 1; } @@ -75767,33 +75666,37 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; switch (rule.action) { case 1: - return; + return 0; case 8: if (previousRange.end !== currentRange.pos) { recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 : 0; } break; case 4: if (rule.flags !== 1 && previousStartLine !== currentStartLine) { - return; + return 0; } var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 : 1; } break; case 2: if (rule.flags !== 1 && previousStartLine !== currentStartLine) { - return; + return 0; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 : 0; } - break; } + return 0; } } var LineAction; @@ -75885,12 +75788,12 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; } - return spaces ? tabString + repeat(" ", spaces) : tabString; + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; } else { var spacesString = void 0; @@ -75900,20 +75803,13 @@ var ts; internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = ts.repeatString(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { spacesString = internedSpacesIndentation[quotient]; } - return remainder ? spacesString + repeat(" ", remainder) : spacesString; - } - function repeat(value, count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += value; - } - return s; + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; } } formatting.getIndentationString = getIndentationString; @@ -76477,7 +76373,7 @@ var ts; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 : 0, context.formatContext); + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options) === "\n" ? 1 : 0, context.formatContext); }; ChangeTracker.with = function (context, cb) { var tracker = ChangeTracker.fromContext(context); @@ -76966,6 +76862,38 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, false); }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, false); + }; Writer.prototype.writeTextOfNode = function (text, node) { this.writer.writeTextOfNode(text, node); }; @@ -77004,8 +76932,8 @@ var ts; Writer.prototype.isAtStartOfLine = function () { return this.writer.isAtStartOfLine(); }; - Writer.prototype.reset = function () { - this.writer.reset(); + Writer.prototype.clear = function () { + this.writer.clear(); this.lastNonTriviaPosition = 0; }; return Writer; @@ -77141,8 +77069,8 @@ var ts; var refactor; (function (refactor_1) { var refactors = ts.createMap(); - function registerRefactor(refactor) { - refactors.set(refactor.name, refactor); + function registerRefactor(name, refactor) { + refactors.set(name, refactor); } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { @@ -77852,9 +77780,11 @@ var ts; } break; case 147: - var functionDeclaration = parent.parent; - if (functionDeclaration.parameters.length === 1) { - changes.deleteNode(sourceFile, parent); + var oldFunction = parent.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceRange(sourceFile, { pos: oldFunction.getStart(), end: oldFunction.end }, newFunction); } else { changes.deleteNodeInList(sourceFile, parent); @@ -77998,7 +77928,7 @@ var ts; return { span: ts.createTextSpanFromBounds(declaration.getStart(sourceFile), declaration.getEnd()), newText: newText }; } function typeString(type, checker) { - return checker.typeToString(type, undefined, 8); + return checker.typeToString(type, undefined, 1); } function isTypeContainer(node) { switch (node.kind) { @@ -78208,7 +78138,6 @@ var ts; var symbolToken = ts.cast(ts.getTokenAtPosition(context.sourceFile, context.span.start, false), ts.isIdentifier); return { host: context.host, - newLineCharacter: context.newLineCharacter, formatContext: context.formatContext, sourceFile: context.sourceFile, program: program, @@ -78423,7 +78352,7 @@ var ts; } function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { var roots = ts.getEffectiveTypeRoots(options, host); - return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + 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), options, addJsExtension); @@ -78764,10 +78693,11 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, newLineCharacter = context.newLineCharacter, span = context.span; + var sourceFile = context.sourceFile, program = context.program, span = context.span; if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } + var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)])], @@ -78788,7 +78718,7 @@ var ts; fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { if (err.start !== undefined) { - changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, context.newLineCharacter)); + changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options))); } }); }, }); @@ -78858,8 +78788,8 @@ var ts; outputMethod(signature, modifiers, name, createStubbedMethodBody()); break; } - for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { - var signature = signatures_9[_i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var signature = signatures_8[_i]; outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); } if (declarations.length > signatures.length) { @@ -78879,7 +78809,7 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152, enclosingDeclaration, 256); if (!signatureDeclaration) { return undefined; } @@ -78912,8 +78842,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var _i = 0, signatures_10 = signatures; _i < signatures_10.length; _i++) { - var sig = signatures_10[_i]; + for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { + var sig = signatures_9[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -79137,7 +79067,7 @@ var ts; var typeIsAccessible = true; var writeText = function (text) { return str += text; }; return { - string: function () { return typeIsAccessible ? str : undefined; }, + getText: function () { return typeIsAccessible ? str : undefined; }, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -79146,6 +79076,15 @@ var ts; writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + write: writeText, + writeTextOfNode: writeText, + rawWrite: writeText, + writeLiteral: writeText, + getTextPos: function () { return 0; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return writeText(" "); }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -79162,8 +79101,8 @@ var ts; } function typeToString(type, enclosingDeclaration, checker) { var writer = getTypeAccessiblityWriter(checker); - checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); - return writer.string(); + checker.writeType(type, enclosingDeclaration, undefined, writer); + return writer.getText(); } var InferFromReference; (function (InferFromReference) { @@ -79579,14 +79518,10 @@ var ts; (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { + var refactorName = "Annotate with type from JSDoc"; var actionName = "annotate"; - var annotateTypeFromJSDoc = { - name: "Annotate with type from JSDoc", - description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(annotateTypeFromJSDoc); + var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; @@ -79594,11 +79529,11 @@ var ts; var node = ts.getTokenAtPosition(context.file, context.startPosition, false); if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: annotateTypeFromJSDoc.name, - description: annotateTypeFromJSDoc.description, + name: refactorName, + description: description, actions: [ { - description: annotateTypeFromJSDoc.description, + description: description, name: actionName } ] @@ -79802,15 +79737,11 @@ var ts; var refactor; (function (refactor) { var convertFunctionToES6Class; - (function (convertFunctionToES6Class_1) { + (function (convertFunctionToES6Class) { + var refactorName = "Convert to ES2015 class"; var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); + var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!ts.isInJavaScriptFile(context.file)) { return undefined; @@ -79825,11 +79756,11 @@ var ts; if ((symbol.flags & 16) && symbol.members && (symbol.members.size > 0)) { return [ { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, + name: refactorName, + description: description, actions: [ { - description: convertFunctionToES6Class.description, + description: description, name: actionName } ] @@ -80022,13 +79953,8 @@ var ts; var refactor; (function (refactor) { var actionName = "Convert to ES6 module"; - var convertToEs6Module = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(convertToEs6Module); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition; if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { @@ -80037,11 +79963,11 @@ var ts; var node = ts.getTokenAtPosition(file, startPosition, false); return !isAtTriggerLocation(file, node) ? undefined : [ { - name: convertToEs6Module.name, - description: convertToEs6Module.description, + name: actionName, + description: description, actions: [ { - description: convertToEs6Module.description, + description: description, name: actionName, }, ], @@ -80454,14 +80380,9 @@ var ts; var refactor; (function (refactor) { var extractSymbol; - (function (extractSymbol_1) { - var extractSymbol = { - name: "Extract Symbol", - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction, - }; - refactor.registerRefactor(extractSymbol); + (function (extractSymbol) { + 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 targetRange = rangeToExtract.targetRange; @@ -80504,21 +80425,21 @@ var ts; var infos = []; if (functionActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), actions: functionActions }); } if (constantActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), actions: constantActions }); } return infos.length ? infos : undefined; } - extractSymbol_1.getAvailableActions = getAvailableActions; + extractSymbol.getAvailableActions = getAvailableActions; function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); var targetRange = rangeToExtract.targetRange; @@ -80536,7 +80457,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol_1.getEditsForAction = getEditsForAction; + extractSymbol.getEditsForAction = getEditsForAction; var Messages; (function (Messages) { function createMessage(message) { @@ -80564,7 +80485,7 @@ var ts; Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -80811,7 +80732,7 @@ var ts; } } } - extractSymbol_1.getRangeToExtract = getRangeToExtract; + extractSymbol.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -80983,7 +80904,7 @@ var ts; if (!isJS) { var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, 1); } var paramDecl = ts.createParameter(undefined, undefined, undefined, name, undefined, typeNode); parameters.push(paramDecl); @@ -81002,7 +80923,7 @@ var ts; : undefined; if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); + returnType = checker.typeToTypeNode(contextualType, scope, 1); } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -81053,7 +80974,7 @@ var ts; for (var _i = 0, exposedVariableDeclarations_1 = exposedVariableDeclarations; _i < exposedVariableDeclarations_1.length; _i++) { var variableDeclaration = exposedVariableDeclarations_1[_i]; bindingElements.push(ts.createBindingElement(undefined, undefined, ts.getSynthesizedDeepClone(variableDeclaration.name))); - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1); typeElements.push(ts.createPropertySignature(undefined, variableDeclaration.symbol.name, undefined, variableType, undefined)); sawExplicitType = sawExplicitType || variableDeclaration.type !== undefined; commonNodeFlags = commonNodeFlags & variableDeclaration.parent.flags; @@ -81141,7 +81062,7 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1); var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -81766,15 +81687,11 @@ var ts; var refactor; (function (refactor) { var installTypesForPackage; - (function (installTypesForPackage_1) { + (function (installTypesForPackage) { + var refactorName = "Install missing types package"; var actionName = "install"; - var installTypesForPackage = { - name: "Install missing types package", - description: "Install missing types package", - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(installTypesForPackage); + var description = "Install missing types package"; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { return undefined; @@ -81782,8 +81699,8 @@ var ts; var action = getAction(context); return action && [ { - name: installTypesForPackage.name, - description: installTypesForPackage.description, + name: refactorName, + description: description, actions: [ { description: action.description, @@ -81834,13 +81751,8 @@ var ts; var installTypesForPackage; (function (installTypesForPackage) { var actionName = "Convert to default import"; - var useDefaultImport = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(useDefaultImport); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition, program = context.program; if (!program.getCompilerOptions().allowSyntheticDefaultImports) { @@ -81857,11 +81769,11 @@ var ts; } return [ { - name: useDefaultImport.name, - description: useDefaultImport.description, + name: actionName, + description: description, actions: [ { - description: useDefaultImport.description, + description: description, name: actionName, }, ], @@ -82409,9 +82321,9 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_7 = ts.getTextOfIdentifierOrLiteral(name); - if (result_7 !== undefined) { - return result_7; + var result_6 = ts.getTextOfIdentifierOrLiteral(name); + if (result_6 !== undefined) { + return result_6; } if (name.kind === 145) { var expr = name.expression; @@ -82671,8 +82583,7 @@ var ts; sourceFile.scriptSnapshot = scriptSnapshot; } function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { - var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); return sourceFile; } @@ -82808,7 +82719,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -82817,7 +82728,7 @@ var ts; var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache.getEntryByPath(path); if (entry) { - return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } return host.readFile && host.readFile(fileName); }, @@ -83241,20 +83152,18 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } function getCombinedCodeFix(scope, fixId, formatOptions) { synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -83369,7 +83278,6 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, @@ -83490,20 +83398,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_8 = []; + 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_8.push(symbol); + result_7.push(symbol); } }); - return result_8; + return result_7; } if (symbol) { - result_8.push(symbol); - return result_8; + result_7.push(symbol); + return result_7; } } return undefined; @@ -84057,7 +83965,7 @@ var ts; CoreServicesShimObject.prototype.getPreProcessedFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), true, true); + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), true, true); return { referencedFiles: _this.convertFileReferences(result.referencedFiles), importedFiles: _this.convertFileReferences(result.importedFiles), @@ -84092,8 +84000,7 @@ var ts; CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { - var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseJsonText(fileName, text); + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); var normalizedFileName = ts.normalizeSlashes(fileName); var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), {}, normalizedFileName); return { @@ -84754,6 +84661,7 @@ var ts; this.textStorage = new TextStorage(host, fileName); if (hasMixedContent || this.isDynamic) { this.textStorage.reload(""); + this.realpath = this.path; } this.scriptKind = scriptKind ? scriptKind @@ -84787,6 +84695,25 @@ var ts; ScriptInfo.prototype.getSnapshot = function () { return this.textStorage.getSnapshot(); }; + ScriptInfo.prototype.ensureRealPath = function () { + if (this.realpath === undefined) { + this.realpath = this.path; + if (this.host.realpath) { + ts.Debug.assert(!!this.containingProjects.length); + var project = this.containingProjects[0]; + var realpath = this.host.realpath(this.path); + if (realpath) { + this.realpath = project.toPath(realpath); + if (this.realpath !== this.path) { + project.projectService.realpathToScriptInfos.add(this.realpath, this); + } + } + } + } + }; + ScriptInfo.prototype.getRealpathIfDifferent = function () { + return this.realpath && this.realpath !== this.path ? this.realpath : undefined; + }; ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatCodeSettings; }; @@ -84794,6 +84721,9 @@ var ts; var isNew = !this.isAttached(project); if (isNew) { this.containingProjects.push(project); + if (!project.getCompilerOptions().preserveSymlinks) { + this.ensureRealPath(); + } } return isNew; }; @@ -84831,7 +84761,7 @@ var ts; for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; if (p.projectKind === server.ProjectKind.Configured) { - p.directoryStructureHost.addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); + p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); } var isInfoRoot = p.isRoot(this); p.removeFile(this, false, false); @@ -84879,8 +84809,7 @@ var ts; return this.textStorage.getVersion(); }; ScriptInfo.prototype.saveTo = function (fileName) { - var snap = this.textStorage.getSnapshot(); - this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot())); }; ScriptInfo.prototype.delayReloadNonMixedContentFile = function () { ts.Debug.assert(!this.isDynamicOrHasMixedContent()); @@ -84933,6 +84862,168 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + catch (_e) { + ts.Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + if (!host.directoryExists) { + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + clearCache(); + } + else { + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; var ConfigFileProgramReloadLevel; (function (ConfigFileProgramReloadLevel) { ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; @@ -84969,6 +85060,13 @@ var ts; } } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; function addFileWatcher(host, file, cb) { return host.watchFile(file, cb); } @@ -85046,7 +85144,7 @@ var ts; var ts; (function (ts) { ts.maxNumberOfFilesToIterateForInvalidation = 256; - function createResolutionCache(resolutionHost, rootDirForResolution) { + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var allFilesHaveInvalidatedResolution = false; @@ -85055,6 +85153,7 @@ var ts; var resolvedTypeReferenceDirectives = ts.createMap(); var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); var failedLookupDefaultExtensions = [".ts", ".tsx", ".js", ".jsx", ".json"]; var customFailedLookupPaths = ts.createMap(); var directoryWatchesOfFailedLookups = ts.createMap(); @@ -85104,8 +85203,8 @@ var ts; filesWithChangedSetOfUnresolvedImports = undefined; return collected; } - function createHasInvalidatedResolution() { - if (allFilesHaveInvalidatedResolution) { + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { filesWithInvalidatedResolutions = undefined; return ts.returnTrue; } @@ -85216,8 +85315,8 @@ var ts; function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, undefined, false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames, logChanges) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChanges); + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); @@ -85338,8 +85437,8 @@ var ts; function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } if (!allFilesHaveInvalidatedResolution && dirPath === rootPath || isNodeModulesDirectory(dirPath) || ts.getDirectoryPath(fileOrDirectoryPath) === dirPath) { @@ -85417,6 +85516,9 @@ var ts; if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { return false; } + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } } @@ -85431,8 +85533,8 @@ var ts; function createTypeRootsWatch(_typeRootPath, typeRoot) { return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } resolutionHost.onChangedAutomaticTypeDirectiveNames(); }, 1); @@ -85578,6 +85680,243 @@ var ts; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +(function (ts) { + var BuilderState; + (function (BuilderState) { + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + ts.Debug.assert(!!sourceFile); + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + function getAllDependencies(state, programOfThisState, sourceFile) { + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + return getAllFileNames(state, programOfThisState); + } + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + 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) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + var seenFileNamesMap = ts.createMap(); + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +var ts; (function (ts) { var server; (function (server) { @@ -85667,7 +86006,6 @@ var ts; this.documentRegistry = documentRegistry; this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; - this.directoryStructureHost = directoryStructureHost; this.rootFiles = []; this.rootFilesMap = ts.createMap(); this.plugins = []; @@ -85677,6 +86015,7 @@ var ts; this.projectStructureVersion = 0; this.projectStateVersion = 0; this.hasChangedAutomaticTypeDirectiveNames = false; + this.directoryStructureHost = directoryStructureHost; this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { @@ -85695,7 +86034,7 @@ var ts; if (host.realpath) { this.realpath = function (path) { return host.realpath(path); }; } - this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory); + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, true); this.languageService = ts.createLanguageService(this, this.documentRegistry); if (!languageServiceEnabled) { this.disableLanguageService(); @@ -85744,7 +86083,7 @@ var ts; return this.getCompilationSettings(); }; Project.prototype.getNewLine = function () { - return this.directoryStructureHost.newLine; + return this.projectService.host.newLine; }; Project.prototype.getProjectVersion = function () { return this.projectStateVersion.toString(); @@ -85799,20 +86138,20 @@ var ts; return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); }; Project.prototype.useCaseSensitiveFileNames = function () { - return this.directoryStructureHost.useCaseSensitiveFileNames; + return this.projectService.host.useCaseSensitiveFileNames; }; Project.prototype.readDirectory = function (path, extensions, exclude, include, depth) { return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }; Project.prototype.readFile = function (fileName) { - return this.directoryStructureHost.readFile(fileName); + return this.projectService.host.readFile(fileName); }; Project.prototype.fileExists = function (file) { var path = this.toPath(file); return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); }; Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { - return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, true); + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }; Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); @@ -85823,6 +86162,9 @@ var ts; Project.prototype.getDirectories = function (path) { return this.directoryStructureHost.getDirectories(path); }; + Project.prototype.getCachedDirectoryStructureHost = function () { + return undefined; + }; Project.prototype.toPath = function (fileName) { return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); }; @@ -85863,15 +86205,6 @@ var ts; } return this.languageService; }; - Project.prototype.ensureBuilder = function () { - var _this = this; - if (!this.builder) { - this.builder = ts.createBuilder({ - getCanonicalFileName: this.projectService.toCanonicalFileName, - computeHash: function (data) { return _this.projectService.host.createHash(data); } - }); - } - }; Project.prototype.shouldEmitFile = function (scriptInfo) { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); }; @@ -85881,8 +86214,8 @@ var ts; return []; } this.updateGraph(); - this.ensureBuilder(); - return ts.mapDefined(this.builder.getFilesAffectedBy(this.program, scriptInfo.path), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; Project.prototype.emitFile = function (scriptInfo, writeFile) { if (!this.languageServiceEnabled || !this.shouldEmitFile(scriptInfo)) { @@ -85911,6 +86244,7 @@ var ts; } this.languageService.cleanupSemanticCache(); this.languageServiceEnabled = false; + this.builderState = undefined; this.resolutionCache.closeTypeRootsWatch(); this.projectService.onUpdateLanguageServiceStateForProject(this, false); }; @@ -85962,7 +86296,7 @@ var ts; this.rootFilesMap = undefined; this.externalFiles = undefined; this.program = undefined; - this.builder = undefined; + this.builderState = undefined; this.resolutionCache.clear(); this.resolutionCache = undefined; this.cachedUnresolvedImportsPerFile = undefined; @@ -86165,21 +86499,18 @@ var ts; if (this.setTypings(cachedTypings)) { hasChanges = this.updateGraphWorker() || hasChanges; } - if (this.builder) { - this.builder.updateProgram(this.program); - } } else { this.lastCachedUnresolvedImportsList = undefined; - if (this.builder) { - this.builder.clear(); - } } if (hasChanges) { this.projectStructureVersion++; } return !hasChanges; }; + Project.prototype.getCurrentProgram = function () { + return this.program; + }; Project.prototype.removeExistingTypings = function (include) { var existing = ts.getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); return include.filter(function (i) { return existing.indexOf(i) < 0; }); @@ -86240,7 +86571,7 @@ var ts; var _this = this; var fileWatcher = this.projectService.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { if (_this.projectKind === ProjectKind.Configured) { - _this.directoryStructureHost.addOrDeleteFile(fileName, missingFilePath, eventKind); + _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); } if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { _this.missingFilesMap.delete(missingFilePath); @@ -86724,13 +87055,6 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; - function combineProjectOutput(projects, action, comparer, areEqual) { - var outputs = ts.flatMap(projects, action); - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); - } - server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -86814,6 +87138,9 @@ var ts; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); + if (this.host.realpath) { + this.realpathToScriptInfos = ts.createMultiMap(); + } this.currentDirectory = this.host.getCurrentDirectory(); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); @@ -87053,15 +87380,6 @@ var ts; this.refreshInferredProjects(); } }; - ProjectService.prototype.findContainingExternalProject = function (fileName) { - for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - if (proj.containsFile(fileName)) { - return proj; - } - } - return undefined; - }; ProjectService.prototype.getFormatCodeOptions = function (file) { var formatCodeSettings; if (file) { @@ -87091,7 +87409,7 @@ var ts; else if (!info.isScriptOpen()) { if (info.containingProjects.length === 0) { this.stopWatchingScriptInfo(info); - this.filenameToScriptInfo.delete(info.path); + this.deleteScriptInfo(info); } else { info.delayReloadNonMixedContentFile(); @@ -87102,7 +87420,7 @@ var ts; ProjectService.prototype.handleDeletedFile = function (info) { this.stopWatchingScriptInfo(info); if (!info.isScriptOpen()) { - this.filenameToScriptInfo.delete(info.path); + this.deleteScriptInfo(info); var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); this.delayUpdateProjectGraphs(containingProjects); @@ -87245,10 +87563,17 @@ var ts; this.filenameToScriptInfo.forEach(function (info) { if (!info.isScriptOpen() && info.isOrphan()) { _this.stopWatchingScriptInfo(info); - _this.filenameToScriptInfo.delete(info.path); + _this.deleteScriptInfo(info); } }); }; + ProjectService.prototype.deleteScriptInfo = function (info) { + this.filenameToScriptInfo.delete(info.path); + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + this.realpathToScriptInfos.remove(realpath, info); + } + }; ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { @@ -87580,7 +87905,7 @@ var ts; }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; - var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host); + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); var languageServiceEnabled = !this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); @@ -87741,6 +88066,38 @@ var ts; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; + ProjectService.prototype.getSymlinkedProjects = function (info) { + var projects; + if (this.realpathToScriptInfos) { + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + ts.forEach(this.realpathToScriptInfos.get(realpath), combineProjects); + } + ts.forEach(this.realpathToScriptInfos.get(info.path), combineProjects); + } + return projects; + function combineProjects(toAddInfo) { + if (toAddInfo !== info) { + var _loop_12 = function (project) { + if (project.languageServiceEnabled && + !project.getCompilerOptions().preserveSymlinks && + !ts.contains(info.containingProjects, project)) { + if (!projects) { + projects = ts.createMultiMap(); + projects.add(toAddInfo.path, project); + } + else if (!ts.forEachEntry(projects, function (projs, path) { return path === toAddInfo.path ? false : ts.contains(projs, project); })) { + projects.add(toAddInfo.path, project); + } + } + }; + for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { + var project = _a[_i]; + _loop_12(project); + } + } + } + }; ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; ts.Debug.assert(!info.fileWatcher); @@ -87765,14 +88122,15 @@ var ts; return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); }; ProjectService.prototype.getOrCreateScriptInfoWorker = function (fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + var _this = this; ts.Debug.assert(fileContent === undefined || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); var path = server.normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); var info = this.getScriptInfoForPath(path); if (!info) { var isDynamic = server.isDynamicFileName(fileName); - ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "Script info with non-dynamic relative file name can only be open script info"); - ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "Open script files with non rooted disk path opened with current directory context cannot have same canonical names"); - ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "Dynamic files must always have current directory context since containing external project name will always match the script info name."); + ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info"; }); + ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); + ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; } @@ -87907,13 +88265,23 @@ var ts; ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); }; + ProjectService.prototype.findExternalProjetContainingOpenScriptInfo = function (info) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + proj.updateGraph(); + if (proj.containsScriptInfo(info)) { + return proj; + } + } + return undefined; + }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { var _this = this; var configFileName; var sendConfigFileDiagEvent = false; var configFileErrors; var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); - var project = this.findContainingExternalProject(fileName); + var project = this.findExternalProjetContainingOpenScriptInfo(info); if (!project) { configFileName = this.getConfigFileNameForFile(info, projectRootPath); if (configFileName) { @@ -87922,6 +88290,9 @@ var ts; project = this.createConfiguredProject(configFileName); sendConfigFileDiagEvent = true; } + else { + project.updateGraph(); + } } } if (project && !project.languageServiceEnabled) { @@ -87955,13 +88326,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_12 = function (proj) { + var _loop_13 = 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_12(proj); + _loop_13(proj); } }; ProjectService.prototype.synchronizeProjectList = function (knownProjects) { @@ -88082,7 +88453,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_13 = function (name) { + var _loop_14 = 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]; @@ -88097,7 +88468,7 @@ var ts; } } if (rule.exclude) { - var _loop_14 = function (exclude) { + var _loop_15 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -88120,7 +88491,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_14(exclude); + _loop_15(exclude); } } else { @@ -88135,11 +88506,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_13(name); + _loop_14(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_15 = function (i) { + var _loop_16 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -88173,7 +88544,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_15(i); + _loop_16(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -88446,6 +88817,21 @@ var ts; }; } server.toEvent = toEvent; + function isProjectsArray(projects) { + return !!projects.length; + } + function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + var outputs = ts.flatMap(isProjectsArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + if (!isProjectsArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (projects, path) { + var value = getValue(path); + outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); + }); + } + return comparer + ? ts.sortAndDeduplicate(outputs, comparer, areEqual) + : ts.deduplicate(outputs, areEqual); + } var Session = (function () { function Session(opts) { var _this = this; @@ -89143,6 +89529,7 @@ var ts; }; Session.prototype.getProjects = function (args) { var projects; + var symLinkedProjects; if (args.projectFileName) { var project = this.getProject(args.projectFileName); if (project) { @@ -89152,12 +89539,13 @@ var ts; else { var scriptInfo = this.projectService.getScriptInfo(args.file); projects = scriptInfo.containingProjects; + symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); - if (!projects || !projects.length) { + if ((!projects || !projects.length) && !symLinkedProjects) { return server.Errors.ThrowNoProject(); } - return projects; + return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; }; Session.prototype.getDefaultProject = function (args) { if (args.projectFileName) { @@ -89170,6 +89558,7 @@ var ts; return info.getDefaultProject(); }; Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var _this = this; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); @@ -89185,7 +89574,7 @@ var ts; locs: server.emptyArray }; } - var fileSpans = server.combineProjectOutput(projects, function (project) { + var fileSpans = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); if (!renameLocations) { return server.emptyArray; @@ -89218,7 +89607,7 @@ var ts; return { info: renameInfo, locs: locs }; } else { - return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); + return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (p, file) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, undefined, renameLocationIsEqualTo); } function renameLocationIsEqualTo(a, b) { if (a === b) { @@ -89252,6 +89641,7 @@ var ts; } }; Session.prototype.getReferences = function (args, simplifiedResult) { + var _this = this; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var defaultProject = this.getDefaultProject(args); @@ -89266,7 +89656,7 @@ var ts; var nameSpan = nameInfo.textSpan; var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; var nameText = scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { + var refs = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { var references = project.getLanguageService().getReferencesAtPosition(file, position); if (!references) { return server.emptyArray; @@ -89294,7 +89684,7 @@ var ts; }; } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, undefined, ts.equateValues); + return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { return project.getLanguageService().findReferences(file, position); }, undefined, ts.equateValues); } function areReferencesResponseItemsForTheSameLocation(a, b) { if (a && b) { @@ -89504,23 +89894,24 @@ var ts; : result; }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var _this = this; var info = this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file); if (!info) { return server.emptyArray; } - var result = []; - var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; - for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { - var project = projectsToSearch_1[_i]; + var projects = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + var symLinkedProjects = !args.projectFileName && this.projectService.getSymlinkedProjects(info); + return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects, function (project, info) { + var result; if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.getCompilationSettings().noEmit) { - result.push({ + result = { projectFileName: project.getProjectName(), fileNames: project.getCompileOnSaveAffectedFileList(info), projectUsesOutFile: !!project.getCompilationSettings().outFile || !!project.getCompilationSettings().out - }); + }; } - } - return result; + return result; + }); }; Session.prototype.emitFile = function (args) { var _this = this; @@ -89659,7 +90050,10 @@ var ts; var projects = this.getProjects(args); var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; if (simplifiedResult) { - return server.combineProjectOutput(projects, function (project) { + return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { + if (fileName && !file) { + return undefined; + } var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); if (!navItems) { return server.emptyArray; @@ -89690,7 +90084,12 @@ var ts; }, undefined, areNavToItemsForTheSameLocation); } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); }, undefined, navigateToItemIsEqualTo); + return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { + if (fileName && !file) { + return undefined; + } + return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, project.isNonTsProject()); + }, undefined, navigateToItemIsEqualTo); } function navigateToItemIsEqualTo(a, b) { if (a === b) { @@ -89761,9 +90160,7 @@ var ts; var mappedRenameLocation = void 0; if (renameFilename !== undefined && renameLocation !== undefined) { var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); - var snapshot = renameScriptInfo.getSnapshot(); - var oldText = snapshot.getText(0, snapshot.getLength()); - mappedRenameLocation = getLocationInNewDocument(oldText, renameFilename, renameLocation, edits); + mappedRenameLocation = getLocationInNewDocument(ts.getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); } return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(project, edits) }; } @@ -89833,9 +90230,9 @@ var ts; }; Session.prototype.mapCodeAction = function (project, _a) { var _this = this; - var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands, fixId = _a.fixId; var changes = unmappedChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); - return { description: description, changes: changes, commands: commands }; + return { description: description, changes: changes, commands: commands, fixId: fixId }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; @@ -90007,8 +90404,8 @@ var ts; continue; } for (var i = textChanges_3.length - 1; i >= 0; i--) { - var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_7 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_7); + var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_6); } } return text; @@ -90332,7 +90729,7 @@ var ts; return this.index.getText(rangeStart, rangeEnd - rangeStart); }; LineIndexSnapshot.prototype.getLength = function () { - return this.index.root.charCount(); + return this.index.getLength(); }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 3eabea4435a..cd1b577b711 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -639,7 +639,7 @@ declare namespace ts { body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; - type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration; + type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | JSDocFunctionType; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; @@ -877,7 +877,7 @@ declare namespace ts { type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; - type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; @@ -1729,6 +1729,16 @@ declare namespace ts { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; + /** Note that the resulting nodes cannot be checked. */ + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName; + /** Note that the resulting nodes cannot be checked. */ + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression; + /** Note that the resulting nodes cannot be checked. */ + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration; + /** Note that the resulting nodes cannot be checked. */ + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; @@ -1748,7 +1758,8 @@ declare namespace ts { getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; + typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; /** * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead * This will be removed in a future version. @@ -1788,33 +1799,79 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + UseOnlyExternalAliasing = 128, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowThisInObjectLiteral = 32768, + AllowQualifedNameInPlaceOfIdentifier = 65536, + AllowAnonymousIdentifier = 131072, + AllowEmptyUnionOrIntersection = 262144, + AllowEmptyTuple = 524288, + AllowUniqueESSymbolType = 1048576, + AllowEmptyIndexInfoType = 2097152, + IgnoreErrors = 3112960, + InObjectTypeLiteral = 4194304, + InTypeAlias = 8388608, + } + enum TypeFormatFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, SuppressAnyReturnType = 256, - WriteTypeParametersInQualifiedName = 512, - AllowThisInObjectLiteral = 1024, - AllowQualifedNameInPlaceOfIdentifier = 2048, - AllowAnonymousIdentifier = 8192, - AllowEmptyUnionOrIntersection = 16384, - AllowEmptyTuple = 32768, - IgnoreErrors = 60416, - InObjectTypeLiteral = 1048576, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowUniqueESSymbolType = 1048576, + AddUndefined = 131072, + WriteArrowStyleSignature = 262144, + InArrayType = 524288, + InElementType = 2097152, + InFirstTypeArgument = 4194304, InTypeAlias = 8388608, + /** @deprecated */ WriteOwnNameForAnyLike = 0, + NodeBuilderFlagsMask = 9469295, } + enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + AllowAnyNodeKind = 4, + } + /** + * @deprecated + */ interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; - buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; + /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; } - interface SymbolWriter { + /** + * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString + */ + interface SymbolWriter extends SymbolTracker { writeKeyword(text: string): void; writeOperator(text: string): void; writePunctuation(text: string): void; @@ -1827,34 +1884,6 @@ declare namespace ts { increaseIndent(): void; decreaseIndent(): void; clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - reportInaccessibleThisError(): void; - reportPrivateInBaseOfClassExpression(propertyName: string): void; - reportInaccessibleUniqueSymbolError(): void; - } - enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 4, - NoTruncation = 8, - WriteArrowStyleSignature = 16, - WriteOwnNameForAnyLike = 32, - WriteTypeArgumentsOfSignature = 64, - InElementType = 128, - UseFullyQualifiedType = 256, - InFirstTypeArgument = 512, - InTypeAlias = 1024, - SuppressAnyReturnType = 4096, - AddUndefined = 8192, - WriteClassExpressionAsTypeLiteral = 16384, - InArrayType = 32768, - UseAliasDefinedOutsideCurrentScope = 65536, - AllowUniqueESSymbolType = 131072, - } - enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, } enum TypePredicateKind { This = 0, @@ -2149,15 +2178,14 @@ declare namespace ts { declaration?: SignatureDeclaration; } enum InferencePriority { - Contravariant = 1, - NakedTypeVariable = 2, - MappedType = 4, - ReturnType = 8, - NeverType = 16, + NakedTypeVariable = 1, + MappedType = 2, + ReturnType = 4, } interface InferenceInfo { typeParameter: TypeParameter; candidates: Type[]; + contraCandidates: Type[]; inferredType: Type; priority: InferencePriority; topLevel: boolean; @@ -2478,6 +2506,7 @@ declare namespace ts { */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string; + createHash?(data: string): string; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2634,6 +2663,10 @@ declare namespace ts { * collisions. */ printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a list of nodes using the given format flags + */ + printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; /** * Prints a source file as-is, without any emit transformations. */ @@ -2689,6 +2722,13 @@ declare namespace ts { interface PrinterOptions { removeComments?: boolean; newLine?: NewLineKind; + omitTrailingSemicolon?: boolean; + } + interface SymbolTracker { + trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + reportInaccessibleThisError?(): void; + reportPrivateInBaseOfClassExpression?(propertyName: string): void; + reportInaccessibleUniqueSymbolError?(): void; } interface TextSpan { start: number; @@ -2701,6 +2741,71 @@ declare namespace ts { interface SyntaxList extends Node { _children: Node[]; } + enum ListFormat { + None = 0, + SingleLine = 0, + MultiLine = 1, + PreserveLines = 2, + LinesMask = 3, + NotDelimited = 0, + BarDelimited = 4, + AmpersandDelimited = 8, + CommaDelimited = 16, + DelimitersMask = 28, + AllowTrailingComma = 32, + Indented = 64, + SpaceBetweenBraces = 128, + SpaceBetweenSiblings = 256, + Braces = 512, + Parenthesis = 1024, + AngleBrackets = 2048, + SquareBrackets = 4096, + BracketsMask = 7680, + OptionalIfUndefined = 8192, + OptionalIfEmpty = 16384, + Optional = 24576, + PreferNewLine = 32768, + NoTrailingNewLine = 65536, + NoInterveningComments = 131072, + NoSpaceIfEmpty = 262144, + SingleElement = 524288, + Modifiers = 131328, + HeritageClauses = 256, + SingleLineTypeLiteralMembers = 448, + MultiLineTypeLiteralMembers = 65, + TupleTypeElements = 336, + UnionTypeConstituents = 260, + IntersectionTypeConstituents = 264, + ObjectBindingPatternElements = 262576, + ArrayBindingPatternElements = 262448, + ObjectLiteralExpressionProperties = 263122, + ArrayLiteralExpressionElements = 4466, + CommaListElements = 272, + CallExpressionArguments = 1296, + NewExpressionArguments = 9488, + TemplateExpressionSpans = 131072, + SingleLineBlockStatements = 384, + MultiLineBlockStatements = 65, + VariableDeclarationList = 272, + SingleLineFunctionBodyStatements = 384, + MultiLineFunctionBodyStatements = 1, + ClassHeritageClauses = 256, + ClassMembers = 65, + InterfaceMembers = 65, + EnumMembers = 81, + CaseBlockClauses = 65, + NamedImportsOrExportsElements = 432, + JsxElementOrFragmentChildren = 131072, + JsxElementAttributes = 131328, + CaseOrDefaultClauseStatements = 81985, + HeritageClauseTypes = 272, + SourceFileStatements = 65537, + Decorators = 24577, + TypeArguments = 26896, + TypeParameters = 26896, + Parameters = 1296, + IndexSignatureParameters = 4432, + } } declare namespace ts { const versionMajorMinor = "2.7"; @@ -2725,26 +2830,14 @@ declare namespace ts { callback: FileWatcherCallback; mtime?: Date; } - /** - * Partial interface of the System thats needed to support the caching of directory structure - */ - interface DirectoryStructureHost { + interface System { + args: string[]; newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string | undefined; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - exit(exitCode?: number): void; - } - interface System extends DirectoryStructureHost { - args: string[]; getFileSize?(path: string): number; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; /** * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that * use native OS file watching @@ -2752,7 +2845,13 @@ declare namespace ts { watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; getExecutingFilePath(): string; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** * This should be cryptographically secure. @@ -2760,6 +2859,7 @@ declare namespace ts { */ createHash?(data: string): string; getMemoryUsage?(): number; + exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; @@ -3151,8 +3251,10 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; @@ -3296,7 +3398,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; - function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; + function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -3764,17 +3866,6 @@ declare namespace ts { declare namespace ts { function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } -declare namespace ts { - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } -} declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -3985,7 +4076,8 @@ 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; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -4001,6 +4093,10 @@ declare namespace ts { getProgram(): Program; dispose(): void; } + interface CombinedCodeFixScope { + type: "file"; + fileName: string; + } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; includeInsertTextCompletions: boolean; @@ -4078,6 +4174,17 @@ declare namespace ts { */ commands?: CodeActionCommand[]; } + interface CodeFixAction extends CodeAction { + /** + * 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?: {}; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands: ReadonlyArray | undefined; + } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { } @@ -4661,9 +4768,6 @@ declare namespace ts { declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.7"; - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; @@ -4696,6 +4800,8 @@ declare namespace ts.server { }; }; interface ServerHost extends System { + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; setTimeout(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout(timeoutId: any): void; setImmediate(callback: (...args: any[]) => void, ...args: any[]): any; @@ -4924,6 +5030,7 @@ declare namespace ts.server.protocol { DocCommentTemplate = "docCommentTemplate", CompilerOptionsForInferredProjects = "compilerOptionsForInferredProjects", GetCodeFixes = "getCodeFixes", + GetCombinedCodeFix = "getCombinedCodeFix", ApplyCodeActionCommand = "applyCodeActionCommand", GetSupportedCodeFixes = "getSupportedCodeFixes", GetApplicableRefactors = "getApplicableRefactors", @@ -5286,6 +5393,13 @@ declare namespace ts.server.protocol { 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; @@ -5319,6 +5433,14 @@ declare namespace ts.server.protocol { */ errorCodes?: ReadonlyArray; } + interface GetCombinedCodeFixRequestArgs { + scope: GetCombinedCodeFixScope; + fixId: {}; + } + interface GetCombinedCodeFixScope { + type: "file"; + args: FileRequestArgs; + } interface ApplyCodeActionCommandRequestArgs { /** May also be an array of commands. */ command: {}; @@ -6061,7 +6183,7 @@ declare namespace ts.server.protocol { } interface CodeFixResponse extends Response { /** The code actions that are available */ - body?: CodeAction[]; + body?: CodeFixAction[]; } interface CodeAction { /** Description of the code action to display in the UI of the editor */ @@ -6071,6 +6193,17 @@ declare namespace ts.server.protocol { /** 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 { + /** + * 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?: {}; + } /** * Format and format on key response message. */ @@ -7110,7 +7243,7 @@ declare namespace ts.server { private getCombinedCodeFix({scope, fixId}, simplifiedResult); private applyCodeActionCommand(args); private getStartAndEndPosition(args, scriptInfo); - private mapCodeAction(project, {description, changes: unmappedChanges, commands}); + private mapCodeAction(project, {description, changes: unmappedChanges, commands, fixId}); private mapTextChangesToCodeEdits(project, textChanges); private mapTextChangesToCodeEditsUsingScriptinfo(textChanges, scriptInfo); private convertTextChangeToCodeEdit(change, scriptInfo); @@ -7151,6 +7284,7 @@ declare namespace ts.server { open(newText: string): void; close(fileExists?: boolean): void; getSnapshot(): IScriptSnapshot; + private ensureRealPath(); getFormatCodeSettings(): FormatCodeSettings; attachToProject(project: Project): boolean; isAttached(project: Project): boolean; @@ -7204,6 +7338,17 @@ declare namespace ts.server { onProjectClosed(project: Project): void; } } +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} declare namespace ts.server { enum ProjectKind { Inferred = 0, @@ -7247,7 +7392,6 @@ declare namespace ts.server { private documentRegistry; private compilerOptions; compileOnSaveEnabled: boolean; - directoryStructureHost: DirectoryStructureHost; private rootFiles; private rootFilesMap; private program; @@ -7260,7 +7404,7 @@ declare namespace ts.server { languageServiceEnabled: boolean; readonly trace?: (s: string) => void; readonly realpath?: (path: string) => string; - private builder; + private builderState; /** * Set of files names that were updated since the last call to getChangesSinceVersion. */ @@ -7321,7 +7465,6 @@ declare namespace ts.server { getGlobalProjectErrors(): ReadonlyArray; getAllProjectErrors(): ReadonlyArray; getLanguageService(ensureSynchronized?: boolean): LanguageService; - private ensureBuilder(); private shouldEmitFile(scriptInfo); getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[]; /** @@ -7523,10 +7666,6 @@ declare namespace ts.server { function convertCompilerOptions(protocolOptions: protocol.ExternalProjectCompilerOptions): CompilerOptions & protocol.CompileOnSaveMixin; function tryConvertScriptKindName(scriptKindName: protocol.ScriptKindName | ScriptKind): ScriptKind; function convertScriptKindName(scriptKindName: protocol.ScriptKindName): ScriptKind.Unknown | ScriptKind.JS | ScriptKind.JSX | ScriptKind.TS | ScriptKind.TSX; - /** - * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. - */ - function combineProjectOutput(projects: ReadonlyArray, action: (project: Project) => ReadonlyArray, comparer?: (a: T, b: T) => number, areEqual?: (a: T, b: T) => boolean): T[]; interface HostConfiguration { formatCodeOptions: FormatCodeSettings; hostInfo: string; @@ -7643,7 +7782,6 @@ declare namespace ts.server { * @param forceInferredProjectsRefresh when true updates the inferred projects even if there is no pending work to update the files/project structures */ private ensureProjectStructuresUptoDate(forceInferredProjectsRefresh?); - private findContainingExternalProject(fileName); getFormatCodeOptions(file?: NormalizedPath): FormatCodeSettings; private updateProjectGraphs(projects); private onSourceFileChanged(fileName, eventKind); @@ -7662,6 +7800,7 @@ declare namespace ts.server { */ private closeOpenFile(info); private deleteOrphanScriptInfoNotInAnyProject(); + private deleteScriptInfo(info); private configFileExists(configFileName, canonicalConfigFilePath, info); private setConfigFileExistenceByNewConfiguredProject(project); /** @@ -7720,7 +7859,9 @@ declare namespace ts.server { getScriptInfo(uncheckedFileName: string): ScriptInfo; private watchClosedScriptInfo(info); private stopWatchingScriptInfo(info); - getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: DirectoryStructureHost): ScriptInfo; + getOrCreateScriptInfoForNormalizedPath(fileName: NormalizedPath, openedByClient: boolean, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, hostToQueryFileExistsOn?: { + fileExists(path: string): boolean; + }): ScriptInfo; private getOrCreateScriptInfoWorker(fileName, currentDirectory, openedByClient, fileContent?, scriptKind?, hasMixedContent?, hostToQueryFileExistsOn?); /** * This gets the script info for the normalized path. If the path is not rooted disk path then the open script info with project root context is preferred @@ -7761,6 +7902,7 @@ declare namespace ts.server { * @param fileContent is a known version of the file content that is more up to date than the one on disk */ openClientFile(fileName: string, fileContent?: string, scriptKind?: ScriptKind, projectRootPath?: string): OpenConfiguredProjectResult; + private findExternalProjetContainingOpenScriptInfo(info); openClientFileWithNormalizedPath(fileName: NormalizedPath, fileContent?: string, scriptKind?: ScriptKind, hasMixedContent?: boolean, projectRootPath?: NormalizedPath): OpenConfiguredProjectResult; /** * Close file whose contents is managed by the client diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 5abb05e26e4..7967ba04fc4 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -489,14 +489,19 @@ var ts; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); /*@internal*/ - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + 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"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; (function (TokenFlags) { @@ -570,47 +575,70 @@ var ts; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // empty space 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"; // Error handling - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + 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"; // State - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + 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"; // even though `T` can't be accessed in the current scope. - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; // Write symbols's type argument if it is instantiated symbol - // eg. class C { p: T } <-- Show p as C.p here + // eg. class C { p: T } <-- Show p as C.p here // var a: C; // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; @@ -618,6 +646,8 @@ var ts; // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -904,11 +934,9 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; - InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -1191,6 +1219,8 @@ var ts; 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"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -1208,20 +1238,22 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + 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"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + 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"; // Masks // - Additional bitmasks TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; @@ -1305,6 +1337,78 @@ var ts; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + 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"; + // Whitespace + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + // Brackets/Braces + 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"; + // Other + 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"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "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"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "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 = {})); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1407,7 +1511,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1420,6 +1524,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -1563,6 +1668,9 @@ var ts; ts.forEach = forEach; /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -2220,7 +2328,7 @@ var ts; var result = 0; for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { var v = array_5[_i]; - // Note: we need the following type assertion because of GH #17069 + // TODO: Remove the following type assertion once the fix for #17069 is merged result += v[prop]; } return result; @@ -2727,6 +2835,9 @@ var ts; /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; /** Throws an error because a function is not implemented. */ function notImplemented() { throw new Error("Not implemented"); @@ -3131,7 +3242,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */) + if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) return 3; } // Per RFC 1738 'file' URI schema has the shape file:/// @@ -3908,10 +4019,10 @@ var ts; } function Signature() { } // tslint:disable-line no-empty function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0 /* None */; this.modifierFlagsCache = 0 /* None */; this.transformFlags = 0 /* None */; @@ -4051,9 +4162,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; /** @@ -4172,182 +4281,16 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } // tslint:disable-line no-empty ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - /** - * If the readDirectory result was already cached, it returns that - * Otherwise gets result from host and caches it. - * The host request is done under try catch block to avoid caching incorrect result - */ - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - // If there is exception to read directories, dont cache the result and direct the calls to host - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - // Just clear the cache for now - // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated - clearCache(); - } - else { - // This was earlier a file (hence not in cached directory contents) - // or we never cached the directory containing it - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - // Folder added or removed, clear the cache instead of updating the folder and its structure - clearCache(); - } - else { - // No need to update the directory structure, just files - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } - } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -4626,7 +4569,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -4746,7 +4689,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -5342,6 +5290,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5601,7 +5550,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -5710,6 +5659,7 @@ var ts; Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), 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."), @@ -5819,7 +5769,6 @@ var ts; Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -5840,7 +5789,6 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -5863,15 +5811,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: function () { return str += " "; }, @@ -5885,10 +5842,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -5929,6 +5886,12 @@ var ts; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -7333,41 +7296,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 /* EqualsToken */ && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 /* ModuleDeclaration */ && node.body && node.body.kind === 234 /* ModuleDeclaration */ && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -7508,6 +7460,33 @@ var ts; return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208 /* Block */: + case 209 /* VariableStatement */: + case 221 /* WithStatement */: + case 212 /* IfStatement */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 223 /* LabeledStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 225 /* TryStatement */: + case 264 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -8293,7 +8272,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -8933,14 +8924,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0 /* CarriageReturnLineFeed */: return carriageReturnLineFeed; case 1 /* LineFeed */: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; /** @@ -10165,7 +10156,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192 /* AwaitExpression */; + return node.kind === 190 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -10638,7 +10629,7 @@ var ts; /* @internal */ function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. - return ts.isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; // Keywords @@ -13351,8 +13342,8 @@ var ts; case 177 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 161 /* FunctionType */: @@ -18799,7 +18790,6 @@ var ts; scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. - var advanceToken = true; var state = 1 /* SawAsterisk */; var margin = undefined; // + 4 for leading '/** ' @@ -18830,7 +18820,6 @@ var ts; // 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 */` state = 0 /* BeginningOfLine */; - advanceToken = false; margin = undefined; indent++; } @@ -18882,13 +18871,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - t = nextJSDocToken(); - } - else { - advanceToken = true; - t = currentToken; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -18973,7 +18956,8 @@ var ts; // a badly malformed tag should not be added to the list of tags return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -18997,6 +18981,8 @@ var ts; indent = 0; break; case 57 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through case 1 /* EndOfFileToken */: // Done break loop; @@ -19031,7 +19017,7 @@ var ts; } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281 /* JSDocTag */, atToken.pos); @@ -19039,8 +19025,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -19302,34 +19287,44 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 /* Property */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0 /* Property */; + break; case "arg": case "argument": case "param": - return target === 1 /* Parameter */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1 /* Parameter */; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTemplateTag */; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146 /* TypeParameter */); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146 /* TypeParameter */, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -19348,6 +19343,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17 /* OpenBraceToken */); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18 /* CloseBraceToken */); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -20021,7 +20024,7 @@ var ts; }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -22566,7 +22569,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -22580,6 +22585,40 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar" }. + */ + function parseNodeModuleFromPath(path) { + path = ts.normalizePath(path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = removeExtensionAndIndex(path.slice(indexAfterPackageName + 1)); + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function removeExtensionAndIndex(path) { + var noExtension = ts.removeFileExtension(path); + return noExtension === "index" ? "" : ts.removeSuffix(noExtension, "/index"); + } /* @internal */ function directoryProbablyExists(directoryName, host) { // if host does not support 'directoryExists' assume that directory will exist @@ -22670,13 +22709,18 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -22834,13 +22878,18 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + /* @internal */ + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -25383,6 +25432,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); + case 181 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -25391,15 +25442,19 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } if (subtreeFlags & 524288 /* ContainsSpread */ - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 268435456 /* ContainsSuper */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* ContainsDynamicImport */; @@ -25410,19 +25465,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97 /* SuperKeyword */: - return true; - case 180 /* PropertyAccessExpression */: - case 181 /* ElementAccessExpression */: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97 /* SuperKeyword */; - } - return false; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25435,7 +25478,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25456,7 +25499,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25485,7 +25528,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* ParameterExcludes */; + return transformFlags & ~939525441 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25505,7 +25548,7 @@ var ts; transformFlags |= 1024 /* DestructuringAssignment */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -25531,7 +25574,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. @@ -25548,7 +25591,7 @@ var ts; transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25566,7 +25609,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25577,7 +25620,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537920833 /* CatchClauseExcludes */; + return transformFlags & ~940574017 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -25589,7 +25632,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25603,7 +25646,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* ConstructorExcludes */; + return transformFlags & ~1003668801 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -25630,7 +25673,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25648,7 +25691,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -25659,7 +25702,7 @@ var ts; transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -25703,7 +25746,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25735,7 +25778,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -25760,19 +25803,31 @@ var ts; transformFlags |= 32768 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601249089 /* ArrowFunctionExcludes */; + return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 97 /* SuperKeyword */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (transformFlags & 134217728 /* Super */) { + transformFlags ^= 134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 134217728 /* Super */) { + transformFlags &= ~134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25786,7 +25841,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -25802,7 +25857,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25812,7 +25867,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25821,7 +25876,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -25832,7 +25887,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -25841,7 +25896,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~574674241 /* ModuleExcludes */; + return transformFlags & ~977327425 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; @@ -25853,18 +25908,25 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; + return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 536872257 /* NodeExcludes */; + var excludeFlags = 939525441 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 192 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: @@ -25873,8 +25935,6 @@ var ts; case 76 /* ConstKeyword */: case 233 /* EnumDeclaration */: case 268 /* EnumMember */: - case 185 /* TypeAssertionExpression */: - case 203 /* AsExpression */: case 204 /* NonNullExpression */: case 131 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. @@ -25991,7 +26051,8 @@ var ts; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. @@ -26002,11 +26063,11 @@ var ts; if (subtreeFlags & 524288 /* ContainsRest */) { transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 176 /* ArrayBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 177 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; @@ -26019,7 +26080,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; case 179 /* ObjectLiteralExpression */: - excludeFlags = 540087617 /* ObjectLiteralExcludes */; + excludeFlags = 942740801 /* ObjectLiteralExcludes */; if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. @@ -26038,7 +26099,7 @@ var ts; break; case 178 /* ArrayLiteralExpression */: case 183 /* NewExpression */: - excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; if (subtreeFlags & 524288 /* ContainsSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. @@ -26084,27 +26145,27 @@ var ts; case 182 /* CallExpression */: case 183 /* NewExpression */: case 178 /* ArrayLiteralExpression */: - return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; case 234 /* ModuleDeclaration */: - return 574674241 /* ModuleExcludes */; + return 977327425 /* ModuleExcludes */; case 147 /* Parameter */: - return 536872257 /* ParameterExcludes */; + return 939525441 /* ParameterExcludes */; case 188 /* ArrowFunction */: - return 601249089 /* ArrowFunctionExcludes */; + return 1003902273 /* ArrowFunctionExcludes */; case 187 /* FunctionExpression */: case 229 /* FunctionDeclaration */: - return 601281857 /* FunctionExcludes */; + return 1003935041 /* FunctionExcludes */; case 228 /* VariableDeclarationList */: - return 546309441 /* VariableDeclarationListExcludes */; + return 948962625 /* VariableDeclarationListExcludes */; case 230 /* ClassDeclaration */: case 200 /* ClassExpression */: - return 539358529 /* ClassExcludes */; + return 942011713 /* ClassExcludes */; case 153 /* Constructor */: - return 601015617 /* ConstructorExcludes */; + return 1003668801 /* ConstructorExcludes */; case 152 /* MethodDeclaration */: case 154 /* GetAccessor */: case 155 /* SetAccessor */: - return 601015617 /* MethodOrAccessorExcludes */; + return 1003668801 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 133 /* NumberKeyword */: case 130 /* NeverKeyword */: @@ -26123,14 +26184,23 @@ var ts; case 232 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 179 /* ObjectLiteralExpression */: - return 540087617 /* ObjectLiteralExcludes */; + return 942740801 /* ObjectLiteralExcludes */; case 264 /* CatchClause */: - return 537920833 /* CatchClauseExcludes */; + return 940574017 /* CatchClauseExcludes */; case 175 /* ObjectBindingPattern */: case 176 /* ArrayBindingPattern */: - return 537396545 /* BindingPatternExcludes */; + return 940049729 /* BindingPatternExcludes */; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + case 186 /* ParenthesizedExpression */: + case 97 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + return 671089985 /* PropertyAccessExcludes */; default: - return 536872257 /* NodeExcludes */; + return 939525441 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -26432,6 +26502,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -26465,10 +26540,25 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { @@ -26565,7 +26655,12 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -26786,14 +26881,13 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. - var _displayBuilder; 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) { @@ -26830,6 +26924,142 @@ var ts; var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + /** + * @deprecated + */ + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896 /* TypeParameters */, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -26845,10 +27075,12 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. - getDiagnostics(sourceFile, cancellationToken); + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -28064,7 +28296,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -28471,6 +28703,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -28598,97 +28834,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 3112960 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 162 /* ConstructorType */ : 161 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 157 /* ConstructSignature */ : 156 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); - } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8 /* NoTruncation */) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256 /* UseFullyQualifiedType */) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096 /* SuppressAnyReturnType */) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1 /* WriteArrayAsGenericType */) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64 /* WriteTypeArgumentsOfSignature */) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; return undefined; @@ -28725,6 +28995,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140 /* UniqueKeyword */, ts.createKeywordTypeNode(137 /* SymbolKeyword */)); } if (type.flags & 2048 /* Void */) { @@ -28746,10 +29021,13 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -28763,7 +29041,7 @@ var ts; // 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 && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + 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); @@ -28776,7 +29054,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } return undefined; @@ -28802,7 +29080,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); @@ -28811,7 +29089,7 @@ var ts; var symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); @@ -28834,10 +29112,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + 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; + } } } else { @@ -28854,7 +29138,8 @@ var ts; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // 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 } } } @@ -28879,11 +29164,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304 /* InObjectTypeLiteral */; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); @@ -28897,7 +29182,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -28911,12 +29196,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -29009,9 +29299,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455 /* Value */); + } + } var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -29058,12 +29363,22 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); @@ -29082,7 +29397,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256 /* SuppressAnyReturnType */) { if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { returnTypeNode = undefined; } @@ -29090,14 +29405,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + 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, 793064 /* Type */, /*expectsIdentifier*/ true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -29108,7 +29426,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -29134,47 +29452,22 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + 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; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216 /* NoAsciiEscaping */); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -29202,11 +29495,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -29269,6 +29644,9 @@ var ts; * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 /* WriteDefaultSymbolWithoutName */ && symbol.escapedName === "default" /* Default */) { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -29278,7 +29656,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } switch (declaration.kind) { @@ -29297,736 +29675,6 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - /** - * Writes only the name of the symbol out to the writer. Uses the original source text - * for the name of the symbol if it is available to match how the user wrote the name. - */ - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - /** - * Writes a property access or element access with the name of the symbol out to the writer. - * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, - * ensuring that any names written with literals use element accesses. - */ - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" /* Default */ ? "default" /* Default */ : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - else { - writePunctuation(writer, 23 /* DotToken */); - writer.writeSymbol(symbolName, symbol); - } - } - /** - * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope - * Meaning needs to be specified if the enclosing declaration is given - */ - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - // Write type arguments of instantiated class/interface here - if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses - // this to determine if an import it has previously seen (and not written out) needs - // to be written to the file once the walk of the tree is complete. - // - // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree - // up front (for example, during checking) could determine if we need to emit the imports - // and we could then access that data during declaration emit. - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if ( - // 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)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - // Get qualified name if the symbol is not a type parameter - // and there is an enclosing declaration or we specifically - // asked for it - var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - var typeFormatFlag = 256 /* UseFullyQualifiedType */ & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, /*endOfChain*/ true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 /* WriteOwnNameForAnyLike */ | 16384 /* WriteClassExpressionAsTypeLiteral */); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024 /* InTypeAlias */; - // Write undefined/null type as any - if (type.flags & 33585807 /* Intrinsic */) { - // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4 /* Reference */) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - // In a literal enum type with a single member E { A }, E and E.A denote the - // same type. We always display this type simply as E. - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 32768 /* TypeParameter */)) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - } - else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && - ((flags & 65536 /* UseAliasDefinedOutsideCurrentScope */) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024 /* UniqueESSymbol */) { - if (flags & 131072 /* AllowUniqueESSymbolType */) { - writeKeyword(writer, 140 /* UniqueKeyword */); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137 /* SymbolKeyword */); - } - else if (type.flags & 96 /* StringOrNumberLiteral */) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288 /* Index */) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128 /* InElementType */); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - else if (type.flags & 1048576 /* IndexedAccess */) { - writeType(type.objectType, 128 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writeType(type.indexType, 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else { - // Should never get here - // { ... } - writePunctuation(writer, 17 /* OpenBraceToken */); - writeSpace(writer); - writePunctuation(writer, 24 /* DotDotDotToken */); - writeSpace(writer); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26 /* CommaToken */) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 128 /* InElementType */); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - if (pos < end) { - writePunctuation(writer, 27 /* LessThanToken */); - writeType(typeArguments[pos], 512 /* InFirstTypeArgument */); - pos++; - while (pos < end) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - writeType(typeArguments[pos], 0 /* None */); - pos++; - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(typeArguments[0], 128 /* InElementType */ | 32768 /* InArrayType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (type.target.objectFlags & 8 /* Tuple */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { - writeAnonymousType(type, flags); - } - else { - // Write the type reference in the format f.g.C where A and B are type arguments - // for outer type parameters, and f and g are the respective declaring containers of those - // type parameters. - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && 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)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23 /* DotToken */); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - if (type.flags & 131072 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); - } - else { - writeTypeList(type.types, 48 /* AmpersandToken */); - } - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - // If type is an anonymous type literal in a type alias declaration, use type alias name - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - else { - // Recursive usage, use any - writeKeyword(writer, 119 /* AnyKeyword */); - } - } - 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 - // However, in case of class expressions, we want to write both the static side and the instance side. - // We skip adding the static side so that the instance side has a chance to be written - // before checking for circular references. - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - // Anonymous types with no symbol are never circular - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || // is exported function symbol - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 4 /* UseTypeOfFunction */) || // use typeof if format flags specify it - ts.contains(symbolStack, symbol); // it is type of the symbol uses itself recursively - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 103 /* TypeOfKeyword */); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455 /* Value */); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216 /* Optional */) { - writePunctuation(writer, 55 /* QuestionToken */); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128 /* InElementType */) { - return true; - } - else if (flags & 512 /* InFirstTypeArgument */) { - // Add parenthesis around function type for the first type argument to avoid ambiguity - var typeParameters = callSignature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writePunctuation(writer, 18 /* CloseBraceToken */); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - var stringIndexInfo = resolved.objectFlags & 2048 /* ReverseMapped */ && resolved.stringIndexInfo ? - createIndexInfo(anyType, resolved.stringIndexInfo.isReadonly, resolved.stringIndexInfo.declaration) : - resolved.stringIndexInfo; - buildIndexSignatureDisplay(stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */) { - if (p.flags & 4194304 /* Prototype */) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = ts.getCheckFlags(p) & 2048 /* ReverseMapped */ ? anyType : getTypeOfSymbol(p); - if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(t, globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92 /* InKeyword */); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - if (type.declaration.questionToken) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85 /* ExtendsKeyword */); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58 /* EqualsToken */); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { - writePunctuation(writer, 17 /* OpenBraceToken */); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26 /* CommaToken */); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177 /* BindingElement */); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - var flags = 512 /* InFirstTypeArgument */; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - flags = 0 /* None */; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19 /* OpenParenToken */); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20 /* CloseParenToken */); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99 /* ThisKeyword */); - } - writeSpace(writer); - writeKeyword(writer, 126 /* IsKeyword */); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { - return; - } - if (flags & 16 /* WriteArrowStyleSignature */) { - writeSpace(writer); - writePunctuation(writer, 36 /* EqualsGreaterThanToken */); - } - else { - writePunctuation(writer, 56 /* ColonToken */); - } - writeSpace(writer); - var typePredicate = getTypePredicateOfSignature(signature); - if (typePredicate) { - buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1 /* Construct */) { - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - } - if (signature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */)) { - // Instantiated signature, write type arguments instead - // This is achieved by passing in the mapper separately - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - switch (kind) { - case 1 /* Number */: - writeKeyword(writer, 133 /* NumberKeyword */); - break; - case 0 /* String */: - writeKeyword(writer, 136 /* StringKeyword */); - break; - } - writePunctuation(writer, 22 /* CloseBracketToken */); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - if (info.type) { - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - } - else { - writeKeyword(writer, 119 /* AnyKeyword */); - } - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } function isDeclarationVisible(node) { if (node) { var links = getNodeLinks(node); @@ -30164,8 +29812,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { resolutionResults[i] = false; } return false; @@ -30199,6 +29847,10 @@ var ts; if (propertyName === 3 /* ResolvedReturnType */) { return target.resolvedReturnType; } + if (propertyName === 4 /* ResolvedBaseConstraint */) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will @@ -30323,7 +29975,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); @@ -31117,7 +30770,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); return type.resolvedBaseTypes = ts.emptyArray; } if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { @@ -31165,7 +30818,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); } } else { @@ -31690,18 +31343,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4 /* Reference */) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144 /* Intersection */) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -32247,12 +31901,17 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0 /* String */)) { + // getIndexedAccessType returns `any` for X[string] where X doesn't have an index signature. + // to avoid this, return `undefined`. + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -32276,29 +31935,30 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216 /* UnionOrIntersection */) { var types = t.types; @@ -32318,7 +31978,7 @@ var ts; return stringType; } if (t.flags & 1048576 /* IndexedAccess */) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -32334,7 +31994,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -32752,7 +32412,7 @@ var ts; // b) It references `arguments` somewhere var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -33046,12 +32706,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -33123,7 +32783,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */); + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) @@ -33669,8 +33329,8 @@ var ts; function getUnionTypePredicate(signatures) { var first; var types = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var sig = signatures_3[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred) { continue; @@ -33952,42 +33612,64 @@ var ts; } return false; } + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // undefined if no transformation is possible. - function getTransformedIndexedAccessType(type) { + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); + 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 + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a + // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen + // 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 getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { // If the index type is generic, or if the object type is generic and doesn't originate in an expression, // we are performing a higher-order index access where we cannot meaningfully access the properties of the @@ -34916,7 +34598,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -35058,8 +34740,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } if (!message) { if (relation === comparableRelation) { @@ -35540,7 +35222,7 @@ var ts; } else if (target.flags & 1048576 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of S. + // A is the constraint of T. var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -35575,7 +35257,7 @@ var ts; } else if (source.flags & 1048576 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. + // A is the constraint of S. var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { @@ -35583,10 +35265,11 @@ var ts; return result; } } - else if (target.flags & 1048576 /* IndexedAccess */ && source.indexType === target.indexType) { - // if we have indexed access types with identical index types, see if relationship holds for - // the two object types. + else if (target.flags & 1048576 /* IndexedAccess */) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -36743,6 +36426,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -36753,6 +36437,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -36779,7 +36464,7 @@ var ts; function isTypeParameterAtTopLevel(type, typeParameter) { return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - /** Create an object with properties named in the string literal type. Every property has type `{}` */ + /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { @@ -36788,7 +36473,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4 /* Property */, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -36840,7 +36525,9 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : emptyObjectType; + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -36859,6 +36546,7 @@ var ts; if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -36927,18 +36615,20 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - // We give lowest priority to inferences of implicitNeverType (which is used as the - // element type for empty array literals). Thus, inferences from empty array literals - // only matter when no other inferences are made. - var p = priority | (source === implicitNeverType ? 16 /* NeverType */ : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -36961,15 +36651,15 @@ var ts; } } else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -36995,7 +36685,7 @@ var ts; // types in contra-variant positions (such as callback parameters). if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2 /* NakedTypeVariable */; + priority |= 1 /* NakedTypeVariable */; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -37039,9 +36729,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -37077,7 +36767,7 @@ var ts; var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4 /* MappedType */; + priority |= 2 /* MappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -37211,10 +36901,19 @@ var ts; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 1 /* Contravariant */ ? getCommonSubtype(baseCandidates) : - context.flags & 1 /* InferUnionTypes */ || inference.priority & 8 /* ReturnType */ ? getUnionType(baseCandidates, 2 /* Subtype */) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + // If we have inferred 'never' but have contravariant candidates. To get a more specific type we + // infer from the contravariant candidates instead. + if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + // We only have contravariant inferences, infer the best common subtype of those + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -37526,16 +37225,6 @@ var ts; return 8388607 /* All */; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576 /* IndexedAccess */) { - // TODO (weswig): This is a substitute for a lazy negated type to remove the types indicated by the TypeFacts from the (potential) union the IndexedAccess refers to - // - See discussion in https://github.com/Microsoft/TypeScript/pull/19275 for details, and test `strictNullNotNullIndexTypeShouldWork` for current behavior - var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; - var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); - if (result !== baseConstraint) { - return result; - } - return type; - } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -38573,17 +38262,18 @@ var ts; var parent = node.parent; return parent.kind === 180 /* PropertyAccessExpression */ || parent.kind === 182 /* CallExpression */ && parent.expression === node || - parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node; + parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 204 /* NonNullExpression */ || + parent.kind === 177 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } - function getDeclaredOrApparentType(symbol, node) { + function getApparentTypeForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - var type = getTypeOfSymbol(symbol); if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } @@ -38662,7 +38352,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */)) { @@ -38912,6 +38602,15 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. @@ -38946,11 +38645,6 @@ var ts; return type; } } - if (noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -39638,7 +39332,7 @@ var ts; // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); + var signatures = getSignaturesOfType(type, 0 /* Call */); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -40288,8 +39982,8 @@ var ts; if (sourceAttributesType) { // Instantiate in context of source type var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); @@ -40983,7 +40677,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -41234,7 +40928,7 @@ var ts; } function isValidMethodAccess(method, type) { var propType = getTypeOfFuncClassEnumModule(method); - var signatures = getSignaturesOfType(propType, 0 /* Call */); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { var thisType = getThisTypeOfSignature(sig); @@ -41409,8 +41103,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var signature = signatures_5[_i]; + 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 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -41545,7 +41239,7 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -41590,7 +41284,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); } } var thisType = getThisTypeOfSignature(signature); @@ -42139,8 +41833,8 @@ var ts; else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -42150,8 +41844,8 @@ var ts; else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var sig = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -43520,6 +43214,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -45133,8 +44830,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_8 = signatures; _a < signatures_8.length; _a++) { - var signature = signatures_8[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -46276,7 +45973,13 @@ var ts; if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + } checkParameterInitializer(node); } return; @@ -47032,7 +46735,8 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -49384,20 +49088,20 @@ var ts; : unknownType; if (type.flags & 1024 /* UniqueESSymbol */ && type.symbol === symbol) { - flags |= 131072 /* AllowUniqueESSymbolType */; + flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 8192 /* AddUndefined */) { + if (flags & 131072 /* AddUndefined */) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -50547,12 +50251,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 /* ArrayBindingPattern */ || node.name.kind === 175 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); @@ -51011,7 +50718,7 @@ var ts; var node = createSynthesizedNode(71 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; - node.autoGenerateKind = 0 /* None */; + node.autoGenerateFlags = 0 /* None */; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -51026,22 +50733,24 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - /** Create a unique temporary variable. */ - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1 /* Auto */; + name.autoGenerateFlags = 1 /* Auto */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + } return name; } ts.createTempVariable = createTempVariable; /** Create a unique temporary variable for use in a loop. */ function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2 /* Loop */; + name.autoGenerateFlags = 2 /* Loop */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -51050,7 +50759,7 @@ var ts; /** Create a unique name based on the supplied text. */ function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3 /* Unique */; + name.autoGenerateFlags = 3 /* Unique */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -51058,10 +50767,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4 /* Node */; + name.autoGenerateFlags = 4 /* Node */; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; + } nextAutoGenerateId++; return name; } @@ -51359,11 +51070,12 @@ var ts; } ts.updateIndexSignature = updateIndexSignature; /* @internal */ - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -54332,7 +54044,9 @@ var ts; // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence - return e.kind === 195 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || + emittedExpression.kind === 293 /* CommaListExpression */ ? ts.createParen(e) : e; } @@ -54982,6 +54696,7 @@ var ts; /// var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -55116,7 +54831,7 @@ var ts; switch (kind) { // Names case 71 /* Identifier */: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145 /* ComputedPropertyName */: @@ -56187,7 +55902,12 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { // If the right-hand value of the destructuring assignment needs to be preserved (as // is the case when the destructuring assignment is part of a larger expression), // then we need to cache the right-hand value. @@ -56231,6 +55951,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -56258,6 +55998,15 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -57343,11 +57092,14 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. @@ -59516,7 +59268,7 @@ var ts; ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -59530,6 +59282,7 @@ var ts; * just-in-time substitution for `super` expressions inside of async methods. */ var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -59567,6 +59320,83 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 215 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 216 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 217 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 264 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 208 /* Block */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 225 /* TryStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 212 /* IfStatement */: + case 221 /* WithStatement */: + case 223 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } /** * Visits an AwaitExpression node. * @@ -59641,6 +59471,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -59653,10 +59550,17 @@ var ts; // `this` and `arguments` objects to `__awaiter`. The generator function // passed to `__awaiter` is executed inside of the callback to the // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -59672,27 +59576,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -59968,8 +59873,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -68128,6 +68033,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. @@ -69361,6 +69267,43 @@ var ts; if (hint === 1 /* Expression */) { return substituteExpression(node); } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 266 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } return node; } /** @@ -70249,9 +70192,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 /* UseTypeOfFunction */ | - 16384 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); + var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 4 /* WriteDefaultSymbolWithoutName */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -70265,7 +70208,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); errorNameNode = undefined; } } @@ -70503,7 +70446,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); write(";"); writeLine(); return tempVarName; @@ -71744,7 +71687,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -72034,9 +71977,9 @@ var ts; * @param tokenStartPos The start pos of the token. * @param emitCallback The callback used to emit the token. */ - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -72045,7 +71988,7 @@ var ts; if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { @@ -72511,7 +72454,6 @@ var ts; /// var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); /*@internal*/ /** @@ -72531,7 +72473,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -72540,7 +72485,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -72673,7 +72621,7 @@ var ts; ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -72739,16 +72687,29 @@ var ts; var generatedNames; // Set of names generated by the NameGenerator. var tempFlagsStack; // Stack of enclosing name generation scopes. var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { // public API printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, // internal API writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -72771,6 +72732,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -72786,6 +72751,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -72813,7 +72788,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -72839,6 +72814,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0 /* Auto */; + reservedNamesStack = []; comments.reset(); setWriter(/*output*/ undefined); } @@ -72902,7 +72878,9 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { @@ -72911,7 +72889,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -73149,7 +73127,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -73173,7 +73151,7 @@ var ts; case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: case 91 /* ImportKeyword */: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; // Expressions case 178 /* ArrayLiteralExpression */: @@ -73269,25 +73247,27 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); } } // // Identifiers // function emitIdentifier(node) { - write(getTextOfNode(node, /*includeTrivia*/ false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names // function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -73299,36 +73279,46 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } // // Signature elements // function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } // @@ -73337,19 +73327,19 @@ var ts; function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -73358,8 +73348,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -73371,13 +73361,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 /* GetAccessor */ ? "get " : "set "); + writeKeyword(node.kind === 154 /* GetAccessor */ ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -73386,34 +73377,37 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } // // Types // function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -73423,7 +73417,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -73445,34 +73441,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336 /* TupleTypeElements */); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260 /* UnionTypeConstituents */); @@ -73481,29 +73482,29 @@ var ts; emitList(node, node.types, 264 /* IntersectionTypeConstituents */); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -73511,23 +73512,24 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); @@ -73536,20 +73538,24 @@ var ts; // Binding patterns // function emitObjectBindingPattern(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); - write("}"); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - write("["); + writePunctuation("["); emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); - write("]"); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Expressions @@ -73586,7 +73592,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -73612,9 +73618,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -73622,26 +73628,27 @@ var ts; emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -73654,30 +73661,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -73701,7 +73712,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; @@ -73710,7 +73721,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -73738,12 +73749,12 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -73756,17 +73767,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } // @@ -73780,13 +73793,13 @@ var ts; // Statements // function emitBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; @@ -73795,27 +73808,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90 /* IfKeyword */, node.pos, node); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, node); + var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, node); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82 /* ElseKeyword */, node.thenStatement.end, node); + writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212 /* IfStatement */) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -73824,55 +73837,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -73886,58 +73907,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77 /* ContinueKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72 /* BreakKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72 /* BreakKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, /*contextNode*/ contextNode); + pos = writeToken(token, pos, writer, /*contextNode*/ contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -73945,24 +73970,26 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos); - write(";"); + writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); + writeSemicolon(); } // // Declarations // function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { @@ -73971,9 +73998,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -74003,19 +74030,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { // We must emit a function body as a single-line body in the following case: @@ -74048,7 +74075,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -74060,7 +74088,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, body); + writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -74085,17 +74113,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -74103,66 +74135,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* HeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* InterfaceMembers */); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81 /* EnumMembers */); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512 /* GlobalAugmentation */) { - write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234 /* ModuleDeclaration */) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(18 /* CloseBraceToken */, node.clauses.end); + writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71 /* Identifier */) { @@ -74174,23 +74217,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -74200,28 +74250,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -74230,14 +74296,16 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } @@ -74245,9 +74313,10 @@ var ts; // Module references // function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } // // JSX @@ -74258,14 +74327,14 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -74273,45 +74342,46 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -74326,13 +74396,15 @@ var ts; // Clauses // function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -74359,25 +74431,25 @@ var ts; } var format = 81985 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 /* MultiLine */ | 64 /* Indented */); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74 /* CatchKeyword */, node.pos); - write(" "); + var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19 /* OpenParenToken */, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } @@ -74386,7 +74458,8 @@ var ts; // function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); // This is to ensure that we emit comment in the following case: // For example: // obj = { @@ -74404,13 +74477,15 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } @@ -74419,7 +74494,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Top-level nodes @@ -74517,33 +74592,60 @@ var ts; // // Helpers // + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328 /* Modifiers */); - write(" "); + writeSpace(); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); - } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); - } - function emitNodeWithPrefix(prefix, node, emit) { + function emitTypeAnnotation(node) { if (node) { - write(prefix); + writePunctuation(":"); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { - write(" "); + writeSpace(); emit(node); } else { @@ -74557,13 +74659,16 @@ var ts; emitList(parentNode, decorators, 24577 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960 /* TypeArguments */); + emitList(parentNode, typeArguments, 26896 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960 /* TypeParameters */); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360 /* Parameters */); + emitList(parentNode, parameters, 1296 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -74583,7 +74688,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); } else { emitParameters(parentNode, parameters); @@ -74598,6 +74703,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -74616,7 +74738,7 @@ var ts; return; } if (format & 7680 /* BracketsMask */) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -74627,7 +74749,7 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { - write(" "); + writeSpace(); } } else { @@ -74639,7 +74761,7 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } // Increase the indent, if requested. if (format & 64 /* Indented */) { @@ -74648,7 +74770,6 @@ var ts; // Emit each child. var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -74659,10 +74780,10 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new @@ -74675,7 +74796,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { - write(" "); + writeSpace(); } } // Emit this child. @@ -74698,7 +74819,7 @@ var ts; // Write a trailing comma, if requested. var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { - write(","); + writePunctuation(","); } // Emit any trailing comment of the last element in the list // i.e @@ -74706,7 +74827,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. @@ -74718,50 +74839,102 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -74952,6 +75125,7 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } /** * Pop the current name generation scope. @@ -74961,15 +75135,22 @@ var ts; return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } /** * Generate the text for a generated identifier. */ function generateName(name) { - if (name.autoGenerateKind === 4 /* Node */) { + 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.skipNameGenerationScope) { + if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { var savedTempFlags = tempFlags; popNameGenerationScope(/*node*/ undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -74999,7 +75180,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } /** * Returns a value indicating whether a name is unique within a container. @@ -75021,11 +75203,14 @@ var ts; * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. */ - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 /* _i */ ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -75038,6 +75223,9 @@ var ts; ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -75130,11 +75318,11 @@ var ts; * Generates a unique identifier for a node. */ function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 3 /* Unique */: return makeUniqueName(ts.idText(name)); } @@ -75152,7 +75340,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 /* Node */ + && node.autoGenerateFlags === 4 /* Node */ && node.autoGenerateId !== autoGenerateId) { break; } @@ -75163,17 +75351,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0 /* None */] = ""; - delimiters[16 /* CommaDelimited */] = ","; - delimiters[4 /* BarDelimited */] = " |"; - delimiters[8 /* AmpersandDelimited */] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28 /* DelimitersMask */]; - } function createBracketsMap() { var brackets = []; brackets[512 /* Braces */] = ["{", "}"]; @@ -75195,474 +75372,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - // Line separators - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - // Delimiters - 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"; - // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - // Brackets/Braces - 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"; - // Other - 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"; - // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "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"] = 256] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "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"] = 26960] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat || (ListFormat = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - function createBuilder(options) { - var isModuleEmit; - var fileInfos = ts.createMap(); - var semanticDiagnosticsPerFile = ts.createMap(); - /** The map has key by source file's path that has been changed */ - var changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - } - hasShapeChanged.clear(); - allFilesExcludingDefaultLibraryFile = undefined; - ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { - // Add new file info - createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, - // Remove existing file info - onDeleteValue: removeExistingFileInfo, - // We will update in place instead of deleting existing value and adding new one - onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } - }); - } - function registerChangedFile(path) { - changedFilesSet.set(path, true); - // All changed files need to re-evaluate its semantic diagnostics - semanticDiagnosticsPerFile.delete(path); - } - function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - function removeExistingFileInfo(_existingFileInfo, path) { - // Since we dont need to track removed file as changed file - // We can just remove its diagnostics - changedFilesSet.delete(path); - semanticDiagnosticsPerFile.delete(path); - emitHandler.onRemoveSourceFile(path); - } - function updateExistingFileInfo(program, existingInfo, sourceFile) { - if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - var compilerOptions = program.getCompilerOptions(); - if (!changedFilesSet.size) { - return ts.emptyArray; - } - // With --out or --outFile all outputs go into single file, do it only once - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - changedFilesSet.clear(); - return [program.emit(/*targetSourceFile*/ undefined, writeFileCallback)]; - } - var seenFiles = ts.createMap(); - var result; - changedFilesSet.forEach(function (_true, path) { - // Get the affected Files by this program - var affectedFiles = getFilesAffectedBy(program, path); - affectedFiles.forEach(function (affectedFile) { - // Affected files shouldnt have cached diagnostics - semanticDiagnosticsPerFile.delete(affectedFile.path); - if (!seenFiles.has(affectedFile.path)) { - seenFiles.set(affectedFile.path, true); - // Emit the affected file - (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - ts.Debug.assert(changedFilesSet.size === 0); - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - // We dont need to cache the diagnostics just return them from program - return program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken); - } - var diagnostics; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); - } - return diagnostics || ts.emptyArray; - } - function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; - } - // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, diagnostics); - return diagnostics; - } - function clear() { - isModuleEmit = undefined; - emitHandler = undefined; - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - /** - * For script files that contains only ambient external modules, although they are not actually external module files, - * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, - * there are no point to rebuild all script files if these special files have changed. However, if any statement - * in the file is not ambient external module, we treat it as a regular script file. - */ - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - /** - * @return {boolean} indicates if the shape signature has changed since last update. - */ - function updateShapeSignature(program, sourceFile) { - ts.Debug.assert(!!sourceFile); - // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (hasShapeChanged.has(sourceFile.path)) { - return false; - } - hasShapeChanged.set(sourceFile.path, true); - var info = fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); - var prevSignature = info.signature; - var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - /** - * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true - */ - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - // We need to use a set here since the code can contain the same import twice, - // but that will only be one dependency. - // To avoid invernal conversion, the key of the referencedFiles map must be of type Path - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - // Handle triple slash references - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - // Handle type reference directives - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - /** - * Gets all files of the program excluding the default library file - */ - function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { - // Use cached result - if (allFilesExcludingDefaultLibraryFile) { - return allFilesExcludingDefaultLibraryFile; - } - var result; - addSourceFile(firstSourceFile); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - if (sourceFile !== firstSourceFile) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function getFilesAffectedByUpdatedShape(program, sourceFile) { - var options = program.getCompilerOptions(); - // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, - // so returning the file itself is good enough. - if (options && (options.out || options.outFile)) { - return [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - // Changed if we had references - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - // If there are any new references that werent present previously there is change - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - // Otherwise its changed if there are more references previously than now - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - // Remove existing references - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - // add files referencing the removedFilePath, as changed files too - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - // Delete the entry for the removed file path - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.arrayFrom(ts.mapDefinedIterator(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - })); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return [sourceFile]; - } - // Now we need to if each file in the referencedBy list has a shape change as well. - // Because if so, its own referencedBy files need to be saved as well to make the - // emitting result consistent with files on disk. - var seenFileNamesMap = ts.createMap(); - // Start with the paths this file was referenced by - var path = sourceFile.path; - seenFileNamesMap.set(path, sourceFile); - var queue = getReferencedByPaths(path); - while (queue.length > 0) { - var currentPath = queue.pop(); - if (!seenFileNamesMap.has(currentPath)) { - var currentSourceFile = program.getSourceFileByPath(currentPath); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - // Return array of values that needs emit - return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); - } - } - } - ts.createBuilder = createBuilder; })(ts || (ts = {})); /// /// /// -/// var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; @@ -75893,9 +75606,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = 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_5), lastLine = _b.line, lastLineChar = _b.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 hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -76224,7 +75937,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -76634,24 +76348,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - // If the noEmitOnError flag is set, then check if we have any errors so far. If so, - // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we - // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } // Create the emit resolver outside of the "emitTime" tracking code below. That way @@ -76662,7 +76378,7 @@ var ts; // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -77215,7 +76931,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. @@ -77681,6 +77397,19 @@ var ts; hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + return ts.forEachEmittedFile(getEmitHost(), function (_a) { + var jsFilePath = _a.jsFilePath, declarationFilePath = _a.declarationFilePath; + return isSameFile(jsFilePath, file) || + (declarationFilePath && isSameFile(declarationFilePath, file)); + }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } } ts.createProgram = createProgram; /* @internal */ @@ -78711,8 +78440,8 @@ var ts; } } ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); @@ -78965,6 +78694,18 @@ var ts; return true; } ts.addToSeen = addToSeen; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -78979,6 +78720,7 @@ var ts; var lineStart; var indent; resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { displayParts: function () { return displayParts; }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, @@ -78988,8 +78730,18 @@ var ts; writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeSymbol: writeSymbol, writeLine: writeLine, + write: unknownWrite, + writeTextOfNode: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, @@ -79110,14 +78862,17 @@ var ts; /** * The default is CRLF. */ - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; } ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; function lineBreakPart() { return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; + /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -79130,20 +78885,20 @@ var ts; ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - flags |= 65536 /* UseAliasDefinedOutsideCurrentScope */; + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); }); } ts.signatureToDisplayParts = signatureToDisplayParts; @@ -80109,7 +79864,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -80118,8 +79873,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -80442,32 +80197,39 @@ var ts; if (!ts.isTrivia(kind)) { return start; } - // Don't bother with newlines/whitespace. - if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { - continue; - } - // Only bother with the trivia if it at least intersects the span of interest. - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - // Classifying a comment might cause us to reuse the trivia scanner - // (because of jsdoc comments). So after we classify the comment make - // sure we set the scanner position back to where it needs to be. - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - pushClassification(start, width, 1 /* comment */); + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. continue; - } - // for the ||||||| and ======== markers, add a comment for the first line, - // and then lex all subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); - classifyDisabledMergeCode(text, start, end); + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); } } } @@ -81008,10 +80770,12 @@ var ts; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options + var seen = ts.createMap(); if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + var typesName = _a[_i]; + var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + pushResult(moduleName); } } else if (host.getDirectories) { @@ -81023,31 +80787,38 @@ var ts; if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(host, root, span, result); + getCompletionEntriesFromDirectories(root); } } - } - if (host.getDirectories) { // Also get all @types typings installed in visible node_modules directories for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, typesDir, span, result); + getCompletionEntriesFromDirectories(typesDir); } } return result; - } - function getCompletionEntriesFromDirectories(host, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); + function getCompletionEntriesFromDirectories(directory) { + ts.Debug.assert(!!host.getDirectories); + if (tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + var directoryName = ts.getBaseFileName(typeDirectory); + var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + pushResult(moduleName); + } } } } + function pushResult(moduleName) { + if (!seen.has(moduleName)) { + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + seen.set(moduleName, true); + } + } } function findPackageJsons(directory, host) { var paths = []; @@ -81185,16 +80956,19 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; // Keywords at function like body })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && pathCompletionsInfo(entries); } - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); - } var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteral(contextToken) && !ts.isNoSubstitutionTemplateLiteral(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host, log); + } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); @@ -81293,10 +81067,19 @@ var ts; return undefined; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - ts.Debug.assert(!(needsConvertPropertyAccess && !propertyAccessToConvert)); if (needsConvertPropertyAccess && !includeInsertTextCompletions) { return undefined; } + var insertText; + var replacementSpan; + if (kind === 1 /* Global */ && origin && origin.type === "this-type") { + insertText = needsConvertPropertyAccess ? "this[\"" + name + "\"]" : "this." + name; + } + else if (needsConvertPropertyAccess) { + // TODO: GH#20619 Use configured quote style + insertText = "[\"" + name + "\"]"; + replacementSpan = ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end); + } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but // really we should consider passing the meaning for the node so that we don't report @@ -81310,13 +81093,10 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - // TODO: GH#20619 Use configured quote style - insertText: needsConvertPropertyAccess ? "[\"" + name + "\"]" : undefined, - replacementSpan: needsConvertPropertyAccess - ? ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end) - : undefined, - hasAction: trueOrUndefined(needsConvertPropertyAccess || origin !== undefined), + hasAction: trueOrUndefined(!!origin && origin.type === "export"), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, }; } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { @@ -81327,7 +81107,7 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && ts.stripQuotes(origin.moduleSymbol.name); + return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); @@ -81362,68 +81142,81 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } } - function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || !ts.isStringLiteral(node) && !ts.isNoSubstitutionTemplateLiteral(node)) { - return undefined; - } - if (node.parent.kind === 265 /* PropertyAssignment */ && - node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && - node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - var type = typeChecker.getTypeAtLocation(node.parent.expression); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); - } - else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ - || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) - || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker); - return pathCompletionsInfo(entries); - } - else if (ts.isIndexedAccessTypeNode(node.parent.parent)) { - // Get all apparent property names - // i.e. interface Foo { - // foo: string; - // bar: string; - // } - // let x: Foo["/*completion position*/"] - var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); - } - else { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, log) { + switch (node.parent.kind) { + case 174 /* LiteralType */: + switch (node.parent.parent.kind) { + case 160 /* TypeReference */: + // TODO: GH#21168 + return undefined; + case 172 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + default: + return undefined; + } + case 265 /* PropertyAssignment */: + if (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && + node.parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); + } + return fromContextualType(); + case 181 /* ElementAccessExpression */: { + var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + var type = typeChecker.getTypeAtLocation(expression); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + } + break; } + case 182 /* CallExpression */: + case 183 /* NewExpression */: + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: + case 249 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return pathCompletionsInfo(Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker)); + default: + return fromContextualType(); + } + function fromContextualType() { // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" return getStringLiteralCompletionEntriesFromType(getContextualTypeFromParent(node, typeChecker), typeChecker); @@ -81556,7 +81349,7 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -81609,7 +81402,7 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo + return symbolOriginInfo && symbolOriginInfo.type === "export" ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) : { codeActions: undefined, sourceDisplay: undefined }; } @@ -81623,7 +81416,6 @@ var ts; host: host, program: program, checker: checker, - newLineCharacter: host.getNewLine(), compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, @@ -81994,6 +81786,9 @@ var ts; keywordFilters = 2 /* ConstructorParameterKeywords */; return true; } + if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { + keywordFilters = 3 /* FunctionLikeBodyKeywords */; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { // cursor inside class declaration getGetClassLikeCompletionSymbols(classLikeContainer); @@ -82052,6 +81847,17 @@ var ts; } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (options.includeInsertTextCompletions && scopeNode.kind !== 269 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbols.push(symbol); + } + } + } if (options.includeExternalModuleExports) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } @@ -82139,7 +81945,7 @@ var ts; // Don't add a completion for a re-export, only for the original. // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + if (typeChecker.getMergedSymbol(symbol.parent) !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } @@ -82147,10 +81953,10 @@ var ts; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - var origin = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; if (stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; } } }); @@ -82529,6 +82335,21 @@ var ts; } return undefined; } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + }); + return container && container; + } + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -82875,13 +82696,13 @@ var ts; return validIdentiferResult; switch (kind) { case 5 /* None */: - case 1 /* Global */: case 3 /* MemberLike */: return undefined; case 0 /* ObjectPropertyDeclaration */: // TODO: GH#18169 return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2 /* PropertyAccess */: + case 1 /* Global */: // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; case 4 /* String */: @@ -82906,6 +82727,8 @@ var ts; return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); case 2 /* ConstructorParameterKeywords */: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + case 3 /* FunctionLikeBodyKeywords */: + return getFilteredKeywordCompletions(isFunctionLikeBodyCompletionKeywordText); default: ts.Debug.assertNever(keywordFilter); } @@ -82959,6 +82782,24 @@ var ts; function isConstructorParameterCompletionKeywordText(text) { return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); } + function isFunctionLikeBodyCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 123 /* ConstructorKeyword */: + case 115 /* StaticKeyword */: + case 117 /* AbstractKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + return false; + } + return true; + } + function isFunctionLikeBodyCompletionKeywordText(text) { + return isFunctionLikeBodyCompletionKeyword(ts.stringToToken(text)); + } function isEqualityOperatorKind(kind) { switch (kind) { case 34 /* EqualsEqualsEqualsToken */: @@ -84464,7 +84305,7 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifier(symbol, node, checker); + symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker); // Compute the meaning from the location and the symbol it references var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; @@ -84507,7 +84348,7 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifier(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { var parent = node.parent; if (ts.isExportSpecifier(parent)) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); @@ -84516,7 +84357,12 @@ var ts; // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. return checker.getImmediateAliasedSymbol(symbol); } - return symbol; + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }) || symbol; } var SpecialSearchKind; (function (SpecialSearchKind) { @@ -84530,8 +84376,8 @@ var ts; */ var State = /** @class */ (function () { function State(sourceFiles, - /** True if we're searching for constructor references. */ - specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; this.specialSearchKind = specialSearchKind; this.checker = checker; @@ -85845,26 +85691,14 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); if (!type) { return undefined; } if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_5 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(/*to*/ result_5, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); - } - }); - return result_5; + return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(typeChecker, type.symbol, node); + return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function getDefinitionAndBoundSpan(program, sourceFile, position) { @@ -85908,59 +85742,29 @@ var ts; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var result = []; - var declarations = symbol.getDeclarations(); var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - // Just add all the declarations. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (ts.isNewExpressionTarget(location) || location.kind === 123 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - // Find the first class-like declaration and try to get the construct signature. - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } + if (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */ && symbol.flags & 32 /* Class */) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } - return false; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); - } - return false; + function getCallSignatureDefinition() { + return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + function getSignatureDefinition(signatureDeclarations, selectConstructors) { if (!signatureDeclarations) { - return false; + return undefined; } - var declarations = []; - var definition; - for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { - var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 153 /* Constructor */ : isSignatureDeclaration(d)) { - declarations.push(d); - if (d.body) - definition = d; - } - } - if (declarations.length) { - result.push(createDefinitionInfo(definition || ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; - } - return false; + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + : undefined; } } function isSignatureDeclaration(node) { @@ -86102,18 +85906,29 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - ts.forEach(ts.getAllJSDocs(declaration), function (doc) { - if (doc.comment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(ts.textPart(doc.comment)); + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); } - }); + documentationComment.push(ts.textPart(comment)); + } }); return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 289 /* JSDocPropertyTag */: + return [declaration]; + case 288 /* JSDocTypedefTag */: + return [declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; @@ -86144,10 +85959,13 @@ var ts; return comment; } function withNode(node) { - return node.getText() + " " + comment; + return addComment(node.getText()); } function withList(list) { - return list.map(function (x) { return x.getText(); }) + " " + comment; + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; } } /** @@ -86560,8 +86378,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_6.config; + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.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. @@ -88926,6 +88744,7 @@ var ts; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); + var printer = ts.createPrinter({ removeComments: true }); var items = ts.map(candidates, function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; @@ -88941,14 +88760,20 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); } else { isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + } }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -88956,7 +88781,15 @@ var ts; suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + } + else { + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + } }); ts.addRange(suffixDisplayParts, returnTypeParts); return { @@ -88977,7 +88810,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: parameter.name, @@ -88988,7 +88822,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation); + var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: typeParameter.symbol.name, @@ -89123,6 +88958,7 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; + var printer; var documentationFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { @@ -89191,14 +89027,14 @@ var ts; displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -89270,7 +89106,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); @@ -89319,7 +89155,7 @@ var ts; else if (declaration.kind !== 156 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter @@ -89428,7 +89264,8 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -89483,6 +89320,12 @@ var ts; documentation = documentationFromAlias; } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); @@ -89504,7 +89347,7 @@ var ts; if (alias && symbolToDisplay === symbol) { symbolToDisplay = alias; } - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { @@ -89534,7 +89377,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -89549,7 +89392,8 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -91084,29 +90928,32 @@ var ts; return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var indentation = inheritedIndentation; var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta - indentation = startLine === lastIndentedLine - ? indentationOnLastIndentedLine - : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; } - else if (indentation === -1 /* Unknown */) { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; } } - return { - indentation: indentation, - delta: delta - }; + else { + return { indentation: inheritedIndentation, delta: delta }; + } } function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { @@ -91140,67 +90987,55 @@ var ts; case 18 /* CloseBraceToken */: case 22 /* CloseBracketToken */: case 20 /* CloseParenToken */: - return indentation + getEffectiveDelta(delta, container); + return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind, container) { - if (nodeStartLine !== line && node.decorators) { - if (kind === getFirstNonDecoratorTokenOfNode(node)) { - // if this token is the first token following the list of decorators, we do not need to indent - return indentation; - } - } - switch (kind) { - // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: - return indentation; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: { - if (container.kind === 252 /* JsxOpeningElement */ || - container.kind === 253 /* JsxClosingElement */ || - container.kind === 251 /* JsxSelfClosingElement */) { - return indentation; - } - break; - } - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: { - if (container.kind !== 173 /* MappedType */) { - return indentation; - } - break; - } - } - // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; + return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, - getDelta: function (child) { return getEffectiveDelta(delta, child); }, + getDelta: getDelta, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { - if (lineAdded) { - indentation += options.indentSize; - } - else { - indentation -= options.indentSize; - } - if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; - } - else { - delta = 0; - } + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; } } }; - function getEffectiveDelta(delta, child) { + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 17 /* OpenBraceToken */: + case 18 /* CloseBraceToken */: + case 19 /* OpenParenToken */: + case 20 /* CloseParenToken */: + case 82 /* ElseKeyword */: + case 106 /* WhileKeyword */: + case 57 /* AtToken */: + return false; + case 41 /* SlashToken */: + case 29 /* GreaterThanToken */: + switch (container.kind) { + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: + return false; + } + break; + case 21 /* OpenBracketToken */: + case 22 /* CloseBracketToken */: + if (container.kind !== 173 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0; } @@ -91223,7 +91058,7 @@ var ts; // context node is set to parent of the token after processing every token var childContextNode = contextNode; // if there are any tokens that logically belong to node and interleave child nodes - // such tokens will be consumed in processChildNode for for the child that follows them + // such tokens will be consumed in processChildNode for the child that follows them ts.forEachChild(node, function (child) { processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, function (nodes) { @@ -91445,23 +91280,25 @@ var ts; var trimTrailingWhitespaces; var lineAction = 0 /* None */; if (rule) { - applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { - lineAction = 2 /* LineRemoved */; - // Handle the case where the next line is moved to be the end of this line. - // In this case we don't indent the next line in the next pass. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); - } - } - else if (rule.action & 4 /* NewLine */ && currentStartLine === previousStartLine) { - lineAction = 1 /* LineAdded */; - // Handle the case where token2 is moved to the new line. - // In this case we indent token2 in the next pass but we set - // sameLineIndent flag to notify the indenter that the indentation is within the line. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); - } + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; @@ -91609,14 +91446,16 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; switch (rule.action) { case 1 /* Ignore */: // no action required - return; + return 0 /* None */; case 8 /* Delete */: if (previousRange.end !== currentRange.pos) { // delete characters starting from t1.end up to t2.pos exclusive recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } break; case 4 /* NewLine */: @@ -91624,25 +91463,27 @@ var ts; // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; } break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } - break; } + return 0 /* None */; } } var LineAction; @@ -91655,7 +91496,7 @@ var ts; * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword - tokenAtPosition, predicate) { + tokenAtPosition, predicate) { if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { @@ -91754,12 +91595,12 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; } - return spaces ? tabString + repeat(" ", spaces) : tabString; + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; } else { var spacesString = void 0; @@ -91769,20 +91610,13 @@ var ts; internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = ts.repeatString(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { spacesString = internedSpacesIndentation[quotient]; } - return remainder ? spacesString + repeat(" ", remainder) : spacesString; - } - function repeat(value, count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += value; - } - return s; + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; } } formatting.getIndentationString = getIndentationString; @@ -92447,7 +92281,7 @@ var ts; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options) === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); }; ChangeTracker.with = function (context, cb) { var tracker = ChangeTracker.fromContext(context); @@ -93002,6 +92836,38 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeTextOfNode = function (text, node) { this.writer.writeTextOfNode(text, node); }; @@ -93040,8 +92906,8 @@ var ts; Writer.prototype.isAtStartOfLine = function () { return this.writer.isAtStartOfLine(); }; - Writer.prototype.reset = function () { - this.writer.reset(); + Writer.prototype.clear = function () { + this.writer.clear(); this.lastNonTriviaPosition = 0; }; return Writer; @@ -93185,8 +93051,9 @@ var ts; // A map with the refactor code as key, the refactor itself as value // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want var refactors = ts.createMap(); - function registerRefactor(refactor) { - refactors.set(refactor.name, refactor); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { @@ -93946,9 +93813,18 @@ var ts; } break; case 147 /* Parameter */: - var functionDeclaration = parent.parent; - if (functionDeclaration.parameters.length === 1) { - changes.deleteNode(sourceFile, parent); + var oldFunction = parent.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, + /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + // Drop leading and trailing trivia of the new function because we're only going + // to replace the span (vs the full span) of the old function - the old leading + // and trailing trivia will remain. + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceRange(sourceFile, { pos: oldFunction.getStart(), end: oldFunction.end }, newFunction); } else { changes.deleteNodeInList(sourceFile, parent); @@ -94106,7 +93982,7 @@ var ts; return { span: ts.createTextSpanFromBounds(declaration.getStart(sourceFile), declaration.getEnd()), newText: newText }; } function typeString(type, checker) { - return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); + return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */); } function isTypeContainer(node) { // NOTE: Some locations are not handled yet: @@ -94338,7 +94214,6 @@ var ts; var symbolToken = ts.cast(ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false), ts.isIdentifier); return { host: context.host, - newLineCharacter: context.newLineCharacter, formatContext: context.formatContext, sourceFile: context.sourceFile, program: program, @@ -94606,7 +94481,7 @@ var ts; } function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { var roots = ts.getEffectiveTypeRoots(options, host); - return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); if (ts.startsWith(moduleFileName, typeRoot)) { return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); @@ -94986,10 +94861,11 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, newLineCharacter = context.newLineCharacter, span = context.span; + var sourceFile = context.sourceFile, program = context.program, span = context.span; if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } + var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)])], @@ -95011,7 +94887,7 @@ var ts; fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { if (err.start !== undefined) { - changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, context.newLineCharacter)); + changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options))); } }); }, }); @@ -95106,8 +94982,8 @@ var ts; outputMethod(signature, modifiers, name, createStubbedMethodBody()); break; } - for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { - var signature = signatures_9[_i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var signature = signatures_8[_i]; // Need to ensure nodes are fresh each time so they can have different positions. outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); } @@ -95128,7 +95004,7 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); if (!signatureDeclaration) { return undefined; } @@ -95179,8 +95055,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var _i = 0, signatures_10 = signatures; _i < signatures_10.length; _i++) { - var sig = signatures_10[_i]; + for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { + var sig = signatures_9[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -95427,7 +95303,7 @@ var ts; var typeIsAccessible = true; var writeText = function (text) { return str += text; }; return { - string: function () { return typeIsAccessible ? str : undefined; }, + getText: function () { return typeIsAccessible ? str : undefined; }, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -95436,6 +95312,15 @@ var ts; writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + write: writeText, + writeTextOfNode: writeText, + rawWrite: writeText, + writeLiteral: writeText, + getTextPos: function () { return 0; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return writeText(" "); }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -95452,8 +95337,8 @@ var ts; } function typeToString(type, enclosingDeclaration, checker) { var writer = getTypeAccessiblityWriter(checker); - checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); - return writer.string(); + checker.writeType(type, enclosingDeclaration, /*flags*/ undefined, writer); + return writer.getText(); } var InferFromReference; (function (InferFromReference) { @@ -95912,14 +95797,10 @@ var ts; (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { + var refactorName = "Annotate with type from JSDoc"; var actionName = "annotate"; - var annotateTypeFromJSDoc = { - name: "Annotate with type from JSDoc", - description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(annotateTypeFromJSDoc); + var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; @@ -95927,11 +95808,11 @@ var ts; var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: annotateTypeFromJSDoc.name, - description: annotateTypeFromJSDoc.description, + name: refactorName, + description: description, actions: [ { - description: annotateTypeFromJSDoc.description, + description: description, name: actionName } ] @@ -96141,15 +96022,11 @@ var ts; var refactor; (function (refactor) { var convertFunctionToES6Class; - (function (convertFunctionToES6Class_1) { + (function (convertFunctionToES6Class) { + var refactorName = "Convert to ES2015 class"; var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); + var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!ts.isInJavaScriptFile(context.file)) { return undefined; @@ -96164,11 +96041,11 @@ var ts; if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { return [ { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, + name: refactorName, + description: description, actions: [ { - description: convertFunctionToES6Class.description, + description: description, name: actionName } ] @@ -96384,13 +96261,8 @@ var ts; var refactor; (function (refactor) { var actionName = "Convert to ES6 module"; - var convertToEs6Module = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(convertToEs6Module); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition; if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { @@ -96399,11 +96271,11 @@ var ts; var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); return !isAtTriggerLocation(file, node) ? undefined : [ { - name: convertToEs6Module.name, - description: convertToEs6Module.description, + name: actionName, + description: description, actions: [ { - description: convertToEs6Module.description, + description: description, name: actionName, }, ], @@ -96873,14 +96745,9 @@ var ts; var refactor; (function (refactor) { var extractSymbol; - (function (extractSymbol_1) { - var extractSymbol = { - name: "Extract Symbol", - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction, - }; - refactor.registerRefactor(extractSymbol); + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); /** * Compute the associated code actions * Exported for tests. @@ -96938,21 +96805,21 @@ var ts; var infos = []; if (functionActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), actions: functionActions }); } if (constantActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), actions: constantActions }); } return infos.length ? infos : undefined; } - extractSymbol_1.getAvailableActions = getAvailableActions; + extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); @@ -96971,7 +96838,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol_1.getEditsForAction = getEditsForAction; + extractSymbol.getEditsForAction = getEditsForAction; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { @@ -97000,7 +96867,7 @@ var ts; Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -97287,7 +97154,7 @@ var ts; } } } - extractSymbol_1.getRangeToExtract = getRangeToExtract; + extractSymbol.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -97489,7 +97356,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -97517,7 +97384,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -97585,7 +97452,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -97696,7 +97563,7 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -98422,15 +98289,11 @@ var ts; var refactor; (function (refactor) { var installTypesForPackage; - (function (installTypesForPackage_1) { + (function (installTypesForPackage) { + var refactorName = "Install missing types package"; var actionName = "install"; - var installTypesForPackage = { - name: "Install missing types package", - description: "Install missing types package", - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(installTypesForPackage); + var description = "Install missing types package"; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { // Then it will be available via `fixCannotFindModule`. @@ -98439,8 +98302,8 @@ var ts; var action = getAction(context); return action && [ { - name: installTypesForPackage.name, - description: installTypesForPackage.description, + name: refactorName, + description: description, actions: [ { description: action.description, @@ -98495,13 +98358,8 @@ var ts; var installTypesForPackage; (function (installTypesForPackage) { var actionName = "Convert to default import"; - var useDefaultImport = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(useDefaultImport); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition, program = context.program; if (!program.getCompilerOptions().allowSyntheticDefaultImports) { @@ -98518,11 +98376,11 @@ var ts; } return [ { - name: useDefaultImport.name, - description: useDefaultImport.description, + name: actionName, + description: description, actions: [ { - description: useDefaultImport.description, + description: description, name: actionName, }, ], @@ -99133,9 +98991,9 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_7 = ts.getTextOfIdentifierOrLiteral(name); - if (result_7 !== undefined) { - return result_7; + var result_6 = ts.getTextOfIdentifierOrLiteral(name); + if (result_6 !== undefined) { + return result_6; } if (name.kind === 145 /* ComputedPropertyName */) { var expr = name.expression; @@ -99420,8 +99278,7 @@ var ts; sourceFile.scriptSnapshot = scriptSnapshot; } function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { - var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); return sourceFile; } @@ -99585,7 +99442,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -99595,7 +99452,7 @@ var ts; var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache.getEntryByPath(path); if (entry) { - return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } return host.readFile && host.readFile(fileName); }, @@ -100097,20 +99954,18 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } function getCombinedCodeFix(scope, fixId, formatOptions) { synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -100298,7 +100153,6 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, @@ -100434,20 +100288,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_8 = []; + 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_8.push(symbol); + result_7.push(symbol); } }); - return result_8; + return result_7; } if (symbol) { - result_8.push(symbol); - return result_8; + result_7.push(symbol); + return result_7; } } return undefined; @@ -100904,8 +100758,6 @@ var ts; CommandTypes["GetCodeFixes"] = "getCodeFixes"; /* @internal */ CommandTypes["GetCodeFixesFull"] = "getCodeFixes-full"; - // TODO: GH#20538 - /* @internal */ CommandTypes["GetCombinedCodeFix"] = "getCombinedCodeFix"; /* @internal */ CommandTypes["GetCombinedCodeFixFull"] = "getCombinedCodeFix-full"; @@ -101151,6 +101003,24 @@ var ts; }; } server.toEvent = toEvent; + function isProjectsArray(projects) { + return !!projects.length; + } + /** + * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. + */ + function combineProjectOutput(defaultValue, getValue, projects, action, comparer, areEqual) { + var outputs = ts.flatMap(isProjectsArray(projects) ? projects : projects.projects, function (project) { return action(project, defaultValue); }); + if (!isProjectsArray(projects) && projects.symLinkedProjects) { + projects.symLinkedProjects.forEach(function (projects, path) { + var value = getValue(path); + outputs.push.apply(outputs, ts.flatMap(projects, function (project) { return action(project, value); })); + }); + } + return comparer + ? ts.sortAndDeduplicate(outputs, comparer, areEqual) + : ts.deduplicate(outputs, areEqual); + } var Session = /** @class */ (function () { function Session(opts) { var _this = this; @@ -101862,6 +101732,7 @@ var ts; }; Session.prototype.getProjects = function (args) { var projects; + var symLinkedProjects; if (args.projectFileName) { var project = this.getProject(args.projectFileName); if (project) { @@ -101871,13 +101742,14 @@ var ts; else { var scriptInfo = this.projectService.getScriptInfo(args.file); projects = scriptInfo.containingProjects; + symLinkedProjects = this.projectService.getSymlinkedProjects(scriptInfo); } // filter handles case when 'projects' is undefined projects = ts.filter(projects, function (p) { return p.languageServiceEnabled; }); - if (!projects || !projects.length) { + if ((!projects || !projects.length) && !symLinkedProjects) { return server.Errors.ThrowNoProject(); } - return projects; + return symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects; }; Session.prototype.getDefaultProject = function (args) { if (args.projectFileName) { @@ -101890,6 +101762,7 @@ var ts; return info.getDefaultProject(); }; Session.prototype.getRenameLocations = function (args, simplifiedResult) { + var _this = this; var file = server.toNormalizedPath(args.file); var position = this.getPositionInFile(args, file); var projects = this.getProjects(args); @@ -101906,7 +101779,7 @@ var ts; locs: server.emptyArray }; } - var fileSpans = server.combineProjectOutput(projects, function (project) { + var fileSpans = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { var renameLocations = project.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); if (!renameLocations) { return server.emptyArray; @@ -101939,7 +101812,7 @@ var ts; return { info: renameInfo, locs: locs }; } else { - return server.combineProjectOutput(projects, function (p) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, + return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (p, file) { return p.getLanguageService().findRenameLocations(file, position, args.findInStrings, args.findInComments); }, /*comparer*/ undefined, renameLocationIsEqualTo); } function renameLocationIsEqualTo(a, b) { @@ -101975,6 +101848,7 @@ var ts; } }; Session.prototype.getReferences = function (args, simplifiedResult) { + var _this = this; var file = server.toNormalizedPath(args.file); var projects = this.getProjects(args); var defaultProject = this.getDefaultProject(args); @@ -101989,7 +101863,7 @@ var ts; var nameSpan = nameInfo.textSpan; var nameColStart = scriptInfo.positionToLineOffset(nameSpan.start).offset; var nameText = scriptInfo.getSnapshot().getText(nameSpan.start, ts.textSpanEnd(nameSpan)); - var refs = server.combineProjectOutput(projects, function (project) { + var refs = combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { var references = project.getLanguageService().getReferencesAtPosition(file, position); if (!references) { return server.emptyArray; @@ -102017,7 +101891,7 @@ var ts; }; } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().findReferences(file, position); }, + return combineProjectOutput(file, function (path) { return _this.projectService.getScriptInfoForPath(path).fileName; }, projects, function (project, file) { return project.getLanguageService().findReferences(file, position); }, /*comparer*/ undefined, ts.equateValues); } function areReferencesResponseItemsForTheSameLocation(a, b) { @@ -102243,24 +102117,25 @@ var ts; : result; }; Session.prototype.getCompileOnSaveAffectedFileList = function (args) { + var _this = this; var info = this.projectService.getScriptInfoEnsuringProjectsUptoDate(args.file); if (!info) { return server.emptyArray; } - var result = []; // if specified a project, we only return affected file list in this project - var projectsToSearch = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; - for (var _i = 0, projectsToSearch_1 = projectsToSearch; _i < projectsToSearch_1.length; _i++) { - var project = projectsToSearch_1[_i]; + var projects = args.projectFileName ? [this.projectService.findProject(args.projectFileName)] : info.containingProjects; + var symLinkedProjects = !args.projectFileName && this.projectService.getSymlinkedProjects(info); + return combineProjectOutput(info, function (path) { return _this.projectService.getScriptInfoForPath(path); }, symLinkedProjects ? { projects: projects, symLinkedProjects: symLinkedProjects } : projects, function (project, info) { + var result; if (project.compileOnSaveEnabled && project.languageServiceEnabled && !project.getCompilationSettings().noEmit) { - result.push({ + result = { projectFileName: project.getProjectName(), fileNames: project.getCompileOnSaveAffectedFileList(info), projectUsesOutFile: !!project.getCompilationSettings().outFile || !!project.getCompilationSettings().out - }); + }; } - } - return result; + return result; + }); }; Session.prototype.emitFile = function (args) { var _this = this; @@ -102400,7 +102275,10 @@ var ts; var projects = this.getProjects(args); var fileName = args.currentFileOnly ? args.file && ts.normalizeSlashes(args.file) : undefined; if (simplifiedResult) { - return server.combineProjectOutput(projects, function (project) { + return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { + if (fileName && !file) { + return undefined; + } var navItems = project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject()); if (!navItems) { return server.emptyArray; @@ -102432,7 +102310,12 @@ var ts; /*comparer*/ undefined, areNavToItemsForTheSameLocation); } else { - return server.combineProjectOutput(projects, function (project) { return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject()); }, + return combineProjectOutput(fileName, function () { return undefined; }, projects, function (project, file) { + if (fileName && !file) { + return undefined; + } + return project.getLanguageService().getNavigateToItems(args.searchValue, args.maxResultCount, fileName, /*excludeDts*/ project.isNonTsProject()); + }, /*comparer*/ undefined, navigateToItemIsEqualTo); } function navigateToItemIsEqualTo(a, b) { @@ -102504,9 +102387,7 @@ var ts; var mappedRenameLocation = void 0; if (renameFilename !== undefined && renameLocation !== undefined) { var renameScriptInfo = project.getScriptInfoForNormalizedPath(server.toNormalizedPath(renameFilename)); - var snapshot = renameScriptInfo.getSnapshot(); - var oldText = snapshot.getText(0, snapshot.getLength()); - mappedRenameLocation = getLocationInNewDocument(oldText, renameFilename, renameLocation, edits); + mappedRenameLocation = getLocationInNewDocument(ts.getSnapshotText(renameScriptInfo.getSnapshot()), renameFilename, renameLocation, edits); } return { renameLocation: mappedRenameLocation, renameFilename: renameFilename, edits: this.mapTextChangesToCodeEdits(project, edits) }; } @@ -102577,9 +102458,9 @@ var ts; }; Session.prototype.mapCodeAction = function (project, _a) { var _this = this; - var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands; + var description = _a.description, unmappedChanges = _a.changes, commands = _a.commands, fixId = _a.fixId; var changes = unmappedChanges.map(function (change) { return _this.mapTextChangesToCodeEditsUsingScriptinfo(change, project.getScriptInfoForNormalizedPath(server.toNormalizedPath(change.fileName))); }); - return { description: description, changes: changes, commands: commands }; + return { description: description, changes: changes, commands: commands, fixId: fixId }; }; Session.prototype.mapTextChangesToCodeEdits = function (project, textChanges) { var _this = this; @@ -102759,8 +102640,8 @@ var ts; continue; } for (var i = textChanges_3.length - 1; i >= 0; i--) { - var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_7 = _c.length; - text = text.slice(0, start) + newText + text.slice(start + length_7); + var _b = textChanges_3[i], newText = _b.newText, _c = _b.span, start = _c.start, length_6 = _c.length; + text = text.slice(0, start) + newText + text.slice(start + length_6); } } return text; @@ -103099,7 +102980,7 @@ var ts; return this.index.getText(rangeStart, rangeEnd - rangeStart); }; LineIndexSnapshot.prototype.getLength = function () { - return this.index.root.charCount(); + return this.index.getLength(); }; LineIndexSnapshot.prototype.getChangeRange = function (oldSnapshot) { if (oldSnapshot instanceof LineIndexSnapshot && this.cache === oldSnapshot.cache) { @@ -103693,6 +103574,7 @@ var ts; this.textStorage = new TextStorage(host, fileName); if (hasMixedContent || this.isDynamic) { this.textStorage.reload(""); + this.realpath = this.path; } this.scriptKind = scriptKind ? scriptKind @@ -103728,6 +103610,28 @@ var ts; ScriptInfo.prototype.getSnapshot = function () { return this.textStorage.getSnapshot(); }; + ScriptInfo.prototype.ensureRealPath = function () { + if (this.realpath === undefined) { + // Default is just the path + this.realpath = this.path; + if (this.host.realpath) { + ts.Debug.assert(!!this.containingProjects.length); + var project = this.containingProjects[0]; + var realpath = this.host.realpath(this.path); + if (realpath) { + this.realpath = project.toPath(realpath); + // If it is different from this.path, add to the map + if (this.realpath !== this.path) { + project.projectService.realpathToScriptInfos.add(this.realpath, this); + } + } + } + } + }; + /*@internal*/ + ScriptInfo.prototype.getRealpathIfDifferent = function () { + return this.realpath && this.realpath !== this.path ? this.realpath : undefined; + }; ScriptInfo.prototype.getFormatCodeSettings = function () { return this.formatCodeSettings; }; @@ -103735,6 +103639,9 @@ var ts; var isNew = !this.isAttached(project); if (isNew) { this.containingProjects.push(project); + if (!project.getCompilerOptions().preserveSymlinks) { + this.ensureRealPath(); + } } return isNew; }; @@ -103774,7 +103681,7 @@ var ts; for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { var p = _a[_i]; if (p.projectKind === server.ProjectKind.Configured) { - p.directoryStructureHost.addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); + p.getCachedDirectoryStructureHost().addOrDeleteFile(this.fileName, this.path, ts.FileWatcherEventKind.Deleted); } var isInfoRoot = p.isRoot(this); // detach is unnecessary since we'll clean the list of containing projects anyways @@ -103828,8 +103735,7 @@ var ts; return this.textStorage.getVersion(); }; ScriptInfo.prototype.saveTo = function (fileName) { - var snap = this.textStorage.getSnapshot(); - this.host.writeFile(fileName, snap.getText(0, snap.getLength())); + this.host.writeFile(fileName, ts.getSnapshotText(this.textStorage.getSnapshot())); }; /*@internal*/ ScriptInfo.prototype.delayReloadNonMixedContentFile = function () { @@ -103893,6 +103799,181 @@ var ts; /* @internal */ var ts; (function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + 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)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; var ConfigFileProgramReloadLevel; (function (ConfigFileProgramReloadLevel) { ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; @@ -103949,6 +104030,13 @@ var ts; } } ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; function addFileWatcher(host, file, cb) { return host.watchFile(file, cb); } @@ -104030,7 +104118,7 @@ var ts; var ts; (function (ts) { ts.maxNumberOfFilesToIterateForInvalidation = 256; - function createResolutionCache(resolutionHost, rootDirForResolution) { + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { var filesWithChangedSetOfUnresolvedImports; var filesWithInvalidatedResolutions; var allFilesHaveInvalidatedResolution = false; @@ -104042,6 +104130,7 @@ var ts; var resolvedTypeReferenceDirectives = ts.createMap(); var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); /** * These are the extensions that failed lookup files will have by default, * any other extension of failed lookup will be store that path in custom failed lookup path @@ -104102,8 +104191,8 @@ var ts; filesWithChangedSetOfUnresolvedImports = undefined; return collected; } - function createHasInvalidatedResolution() { - if (allFilesHaveInvalidatedResolution) { + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { // Any file asked would have invalidated resolution filesWithInvalidatedResolutions = undefined; return ts.returnTrue; @@ -104224,8 +104313,8 @@ var ts; return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, /*reusedNames*/ undefined, /*logChanges*/ false); } - function resolveModuleNames(moduleNames, containingFile, reusedNames, logChanges) { - return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChanges); + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); } function isNodeModulesDirectory(dirPath) { return ts.endsWith(dirPath, "/node_modules"); @@ -104364,9 +104453,9 @@ var ts; function createDirectoryWatcher(directory, dirPath) { return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { + if (cachedDirectoryStructureHost) { // Since the file existance changed, update the sourceFiles cache - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + 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 @@ -104457,6 +104546,10 @@ var ts; if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { return false; } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; } @@ -104475,9 +104568,9 @@ var ts; // Create new watch and recursive info return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); - if (resolutionHost.getCachedDirectoryStructureHost) { + if (cachedDirectoryStructureHost) { // Since the file existance changed, update the sourceFiles cache - resolutionHost.getCachedDirectoryStructureHost().addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); } // For now just recompile // We could potentially store more data here about whether it was/would be really be used or not @@ -104644,12 +104737,319 @@ var ts; server.TypingsCache = TypingsCache; })(server = ts.server || (ts.server = {})); })(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + 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) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + 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) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); /// /// /// /// /// -/// +/// var ts; (function (ts) { var server; @@ -104738,15 +105138,13 @@ var ts; var Project = /** @class */ (function () { /*@internal*/ function Project( - /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, - /*@internal*/ directoryStructureHost, currentDirectory) { + /*@internal*/ projectName, projectKind, projectService, documentRegistry, hasExplicitListOfFiles, languageServiceEnabled, compilerOptions, compileOnSaveEnabled, directoryStructureHost, currentDirectory) { this.projectName = projectName; this.projectKind = projectKind; this.projectService = projectService; this.documentRegistry = documentRegistry; this.compilerOptions = compilerOptions; this.compileOnSaveEnabled = compileOnSaveEnabled; - this.directoryStructureHost = directoryStructureHost; this.rootFiles = []; this.rootFilesMap = ts.createMap(); this.plugins = []; @@ -104770,6 +105168,7 @@ var ts; this.projectStateVersion = 0; /*@internal*/ this.hasChangedAutomaticTypeDirectiveNames = false; + this.directoryStructureHost = directoryStructureHost; this.currentDirectory = this.projectService.getNormalizedAbsolutePath(currentDirectory || ""); this.cancellationToken = new ts.ThrottledCancellationToken(this.projectService.cancellationToken, this.projectService.throttleWaitMilliseconds); if (!this.compilerOptions) { @@ -104790,7 +105189,7 @@ var ts; this.realpath = function (path) { return host.realpath(path); }; } // Use the current directory as resolution root only if the project created using current directory string - this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory); + this.resolutionCache = ts.createResolutionCache(this, currentDirectory && this.currentDirectory, /*logChangesWhenResolvingModule*/ true); this.languageService = ts.createLanguageService(this, this.documentRegistry); if (!languageServiceEnabled) { this.disableLanguageService(); @@ -104841,7 +105240,7 @@ var ts; return this.getCompilationSettings(); }; Project.prototype.getNewLine = function () { - return this.directoryStructureHost.newLine; + return this.projectService.host.newLine; }; Project.prototype.getProjectVersion = function () { return this.projectStateVersion.toString(); @@ -104898,13 +105297,13 @@ var ts; return ts.combinePaths(nodeModuleBinDir, ts.getDefaultLibFileName(this.compilerOptions)); }; Project.prototype.useCaseSensitiveFileNames = function () { - return this.directoryStructureHost.useCaseSensitiveFileNames; + return this.projectService.host.useCaseSensitiveFileNames; }; Project.prototype.readDirectory = function (path, extensions, exclude, include, depth) { return this.directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }; Project.prototype.readFile = function (fileName) { - return this.directoryStructureHost.readFile(fileName); + return this.projectService.host.readFile(fileName); }; Project.prototype.fileExists = function (file) { // As an optimization, don't hit the disks for files we already know don't exist @@ -104913,7 +105312,7 @@ var ts; return !this.isWatchedMissingFile(path) && this.directoryStructureHost.fileExists(file); }; Project.prototype.resolveModuleNames = function (moduleNames, containingFile, reusedNames) { - return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, /*logChanges*/ true); + return this.resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }; Project.prototype.resolveTypeReferenceDirectives = function (typeDirectiveNames, containingFile) { return this.resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); @@ -104925,6 +105324,10 @@ var ts; return this.directoryStructureHost.getDirectories(path); }; /*@internal*/ + Project.prototype.getCachedDirectoryStructureHost = function () { + return undefined; + }; + /*@internal*/ Project.prototype.toPath = function (fileName) { return ts.toPath(fileName, this.currentDirectory, this.projectService.toCanonicalFileName); }; @@ -104974,15 +105377,6 @@ var ts; } return this.languageService; }; - Project.prototype.ensureBuilder = function () { - var _this = this; - if (!this.builder) { - this.builder = ts.createBuilder({ - getCanonicalFileName: this.projectService.toCanonicalFileName, - computeHash: function (data) { return _this.projectService.host.createHash(data); } - }); - } - }; Project.prototype.shouldEmitFile = function (scriptInfo) { return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent(); }; @@ -104992,8 +105386,8 @@ var ts; return []; } this.updateGraph(); - this.ensureBuilder(); - return ts.mapDefined(this.builder.getFilesAffectedBy(this.program, scriptInfo.path), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); + this.builderState = ts.BuilderState.create(this.program, this.projectService.toCanonicalFileName, this.builderState); + return ts.mapDefined(ts.BuilderState.getFilesAffectedBy(this.builderState, this.program, scriptInfo.path, this.cancellationToken, function (data) { return _this.projectService.host.createHash(data); }), function (sourceFile) { return _this.shouldEmitFile(_this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined; }); }; /** * Returns true if emit was conducted @@ -105025,6 +105419,7 @@ var ts; } this.languageService.cleanupSemanticCache(); this.languageServiceEnabled = false; + this.builderState = undefined; this.resolutionCache.closeTypeRootsWatch(); this.projectService.onUpdateLanguageServiceStateForProject(this, /*languageServiceEnabled*/ false); }; @@ -105082,7 +105477,7 @@ var ts; this.rootFilesMap = undefined; this.externalFiles = undefined; this.program = undefined; - this.builder = undefined; + this.builderState = undefined; this.resolutionCache.clear(); this.resolutionCache = undefined; this.cachedUnresolvedImportsPerFile = undefined; @@ -105313,21 +105708,19 @@ var ts; if (this.setTypings(cachedTypings)) { hasChanges = this.updateGraphWorker() || hasChanges; } - if (this.builder) { - this.builder.updateProgram(this.program); - } } else { this.lastCachedUnresolvedImportsList = undefined; - if (this.builder) { - this.builder.clear(); - } } if (hasChanges) { this.projectStructureVersion++; } return !hasChanges; }; + /* @internal */ + Project.prototype.getCurrentProgram = function () { + return this.program; + }; Project.prototype.removeExistingTypings = function (include) { var existing = ts.getAutomaticTypeDirectiveNames(this.getCompilerOptions(), this.directoryStructureHost); return include.filter(function (i) { return existing.indexOf(i) < 0; }); @@ -105400,7 +105793,7 @@ var ts; var _this = this; var fileWatcher = this.projectService.watchFile(this.projectService.host, missingFilePath, function (fileName, eventKind) { if (_this.projectKind === ProjectKind.Configured) { - _this.directoryStructureHost.addOrDeleteFile(fileName, missingFilePath, eventKind); + _this.getCachedDirectoryStructureHost().addOrDeleteFile(fileName, missingFilePath, eventKind); } if (eventKind === ts.FileWatcherEventKind.Created && _this.missingFilesMap.has(missingFilePath)) { _this.missingFilesMap.delete(missingFilePath); @@ -105984,16 +106377,6 @@ var ts; } } server.convertScriptKindName = convertScriptKindName; - /** - * This helper function processes a list of projects and return the concatenated, sortd and deduplicated output of processing each project. - */ - function combineProjectOutput(projects, action, comparer, areEqual) { - var outputs = ts.flatMap(projects, action); - return comparer - ? ts.sortAndDeduplicate(outputs, comparer, areEqual) - : ts.deduplicate(outputs, areEqual); - } - server.combineProjectOutput = combineProjectOutput; var fileNamePropertyReader = { getFileName: function (x) { return x; }, getScriptKind: function (fileName, extraFileExtensions) { @@ -106110,6 +106493,9 @@ var ts; this.allowLocalPluginLoads = !!opts.allowLocalPluginLoads; this.typesMapLocation = (opts.typesMapLocation === undefined) ? ts.combinePaths(this.getExecutingFilePath(), "../typesMap.json") : opts.typesMapLocation; ts.Debug.assert(!!this.host.createHash, "'ServerHost.createHash' is required for ProjectService"); + if (this.host.realpath) { + this.realpathToScriptInfos = ts.createMultiMap(); + } this.currentDirectory = this.host.getCurrentDirectory(); this.toCanonicalFileName = ts.createGetCanonicalFileName(this.host.useCaseSensitiveFileNames); this.throttledOperations = new server.ThrottledOperations(this.host, this.logger); @@ -106383,15 +106769,6 @@ var ts; this.refreshInferredProjects(); } }; - ProjectService.prototype.findContainingExternalProject = function (fileName) { - for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { - var proj = _a[_i]; - if (proj.containsFile(fileName)) { - return proj; - } - } - return undefined; - }; ProjectService.prototype.getFormatCodeOptions = function (file) { var formatCodeSettings; if (file) { @@ -106423,7 +106800,7 @@ var ts; if (info.containingProjects.length === 0) { // Orphan script info, remove it as we can always reload it on next open file request this.stopWatchingScriptInfo(info); - this.filenameToScriptInfo.delete(info.path); + this.deleteScriptInfo(info); } else { // file has been changed which might affect the set of referenced files in projects that include @@ -106437,7 +106814,7 @@ var ts; this.stopWatchingScriptInfo(info); // TODO: handle isOpen = true case if (!info.isScriptOpen()) { - this.filenameToScriptInfo.delete(info.path); + this.deleteScriptInfo(info); // capture list of projects since detachAllProjects will wipe out original list var containingProjects = info.containingProjects.slice(); info.detachAllProjects(); @@ -106642,10 +107019,17 @@ var ts; if (!info.isScriptOpen() && info.isOrphan()) { // if there are not projects that include this script info - delete it _this.stopWatchingScriptInfo(info); - _this.filenameToScriptInfo.delete(info.path); + _this.deleteScriptInfo(info); } }); }; + ProjectService.prototype.deleteScriptInfo = function (info) { + this.filenameToScriptInfo.delete(info.path); + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + this.realpathToScriptInfos.remove(realpath, info); + } + }; ProjectService.prototype.configFileExists = function (configFileName, canonicalConfigFilePath, info) { var configFileExistenceInfo = this.configFileExistenceInfoCache.get(canonicalConfigFilePath); if (configFileExistenceInfo) { @@ -107050,7 +107434,7 @@ var ts; }; ProjectService.prototype.createConfiguredProject = function (configFileName) { var _this = this; - var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host); + var cachedDirectoryStructureHost = ts.createCachedDirectoryStructureHost(this.host, this.host.getCurrentDirectory(), this.host.useCaseSensitiveFileNames); var _a = this.convertConfigFileContentToProjectOptions(configFileName, cachedDirectoryStructureHost), projectOptions = _a.projectOptions, configFileErrors = _a.configFileErrors, configFileSpecs = _a.configFileSpecs; this.logger.info("Opened configuration file " + configFileName); var languageServiceEnabled = !this.exceededTotalSizeLimitForNonTsFiles(configFileName, projectOptions.compilerOptions, projectOptions.files, fileNamePropertyReader); @@ -107252,6 +107636,44 @@ var ts; ProjectService.prototype.getScriptInfo = function (uncheckedFileName) { return this.getScriptInfoForNormalizedPath(server.toNormalizedPath(uncheckedFileName)); }; + /** + * Returns the projects that contain script info through SymLink + * Note that this does not return projects in info.containingProjects + */ + /*@internal*/ + ProjectService.prototype.getSymlinkedProjects = function (info) { + var projects; + if (this.realpathToScriptInfos) { + var realpath = info.getRealpathIfDifferent(); + if (realpath) { + ts.forEach(this.realpathToScriptInfos.get(realpath), combineProjects); + } + ts.forEach(this.realpathToScriptInfos.get(info.path), combineProjects); + } + return projects; + function combineProjects(toAddInfo) { + if (toAddInfo !== info) { + var _loop_12 = function (project) { + // Add the projects only if they can use symLink targets and not already in the list + if (project.languageServiceEnabled && + !project.getCompilerOptions().preserveSymlinks && + !ts.contains(info.containingProjects, project)) { + if (!projects) { + projects = ts.createMultiMap(); + projects.add(toAddInfo.path, project); + } + else if (!ts.forEachEntry(projects, function (projs, path) { return path === toAddInfo.path ? false : ts.contains(projs, project); })) { + projects.add(toAddInfo.path, project); + } + } + }; + for (var _i = 0, _a = toAddInfo.containingProjects; _i < _a.length; _i++) { + var project = _a[_i]; + _loop_12(project); + } + } + } + }; ProjectService.prototype.watchClosedScriptInfo = function (info) { var _this = this; ts.Debug.assert(!info.fileWatcher); @@ -107279,14 +107701,15 @@ var ts; return this.getOrCreateScriptInfoWorker(fileName, this.currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn); }; ProjectService.prototype.getOrCreateScriptInfoWorker = function (fileName, currentDirectory, openedByClient, fileContent, scriptKind, hasMixedContent, hostToQueryFileExistsOn) { + var _this = this; ts.Debug.assert(fileContent === undefined || openedByClient, "ScriptInfo needs to be opened by client to be able to set its user defined content"); var path = server.normalizedPathToPath(fileName, currentDirectory, this.toCanonicalFileName); var info = this.getScriptInfoForPath(path); if (!info) { var isDynamic = server.isDynamicFileName(fileName); - ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "Script info with non-dynamic relative file name can only be open script info"); - ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "Open script files with non rooted disk path opened with current directory context cannot have same canonical names"); - ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "Dynamic files must always have current directory context since containing external project name will always match the script info name."); + ts.Debug.assert(ts.isRootedDiskPath(fileName) || isDynamic || openedByClient, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nScript info with non-dynamic relative file name can only be open script info"; }); + ts.Debug.assert(!ts.isRootedDiskPath(fileName) || this.currentDirectory === currentDirectory || !this.openFilesWithNonRootedDiskPath.has(this.toCanonicalFileName(fileName)), "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nOpen script files with non rooted disk path opened with current directory context cannot have same canonical names"; }); + ts.Debug.assert(!isDynamic || this.currentDirectory === currentDirectory, "", function () { return JSON.stringify({ fileName: fileName, currentDirectory: currentDirectory, hostCurrentDirectory: _this.currentDirectory, openKeys: ts.arrayFrom(_this.openFilesWithNonRootedDiskPath.keys()) }) + "\nDynamic files must always have current directory context since containing external project name will always match the script info name."; }); // If the file is not opened by client and the file doesnot exist on the disk, return if (!openedByClient && !isDynamic && !(hostToQueryFileExistsOn || this.host).fileExists(fileName)) { return; @@ -107485,13 +107908,24 @@ var ts; ProjectService.prototype.openClientFile = function (fileName, fileContent, scriptKind, projectRootPath) { return this.openClientFileWithNormalizedPath(server.toNormalizedPath(fileName), fileContent, scriptKind, /*hasMixedContent*/ false, projectRootPath ? server.toNormalizedPath(projectRootPath) : undefined); }; + ProjectService.prototype.findExternalProjetContainingOpenScriptInfo = function (info) { + for (var _i = 0, _a = this.externalProjects; _i < _a.length; _i++) { + var proj = _a[_i]; + // Ensure project structure is uptodate to check if info is present in external project + proj.updateGraph(); + if (proj.containsScriptInfo(info)) { + return proj; + } + } + return undefined; + }; ProjectService.prototype.openClientFileWithNormalizedPath = function (fileName, fileContent, scriptKind, hasMixedContent, projectRootPath) { var _this = this; var configFileName; var sendConfigFileDiagEvent = false; var configFileErrors; var info = this.getOrCreateScriptInfoOpenedByClientForNormalizedPath(fileName, projectRootPath ? this.getNormalizedAbsolutePath(projectRootPath) : this.currentDirectory, fileContent, scriptKind, hasMixedContent); - var project = this.findContainingExternalProject(fileName); + var project = this.findExternalProjetContainingOpenScriptInfo(info); if (!project) { configFileName = this.getConfigFileNameForFile(info, projectRootPath); if (configFileName) { @@ -107501,6 +107935,10 @@ var ts; // Send the event only if the project got created as part of this open request sendConfigFileDiagEvent = true; } + else { + // Ensure project is ready to check if it contains opened script info + project.updateGraph(); + } } } if (project && !project.languageServiceEnabled) { @@ -107551,13 +107989,13 @@ var ts; this.printProjects(); }; ProjectService.prototype.collectChanges = function (lastKnownProjectVersions, currentProjects, result) { - var _loop_12 = function (proj) { + var _loop_13 = 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_12(proj); + _loop_13(proj); } }; /* @internal */ @@ -107689,7 +108127,7 @@ var ts; var excludeRules = []; var normalizedNames = rootFiles.map(function (f) { return ts.normalizeSlashes(f.fileName); }); var excludedFiles = []; - var _loop_13 = function (name) { + var _loop_14 = 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]; @@ -107707,7 +108145,7 @@ var ts; } } if (rule.exclude) { - var _loop_14 = function (exclude) { + var _loop_15 = function (exclude) { var processedRule = root.replace(rule.match, function () { var groups = []; for (var _i = 0; _i < arguments.length; _i++) { @@ -107734,7 +108172,7 @@ var ts; }; for (var _c = 0, _d = rule.exclude; _c < _d.length; _c++) { var exclude = _d[_c]; - _loop_14(exclude); + _loop_15(exclude); } } else { @@ -107750,11 +108188,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_13(name); + _loop_14(name); } var excludeRegexes = excludeRules.map(function (e) { return new RegExp(e, "i"); }); var filesToKeep = []; - var _loop_15 = function (i) { + var _loop_16 = function (i) { if (excludeRegexes.some(function (re) { return re.test(normalizedNames[i]); })) { excludedFiles.push(normalizedNames[i]); } @@ -107792,7 +108230,7 @@ var ts; }; var this_3 = this; for (var i = 0; i < proj.rootFiles.length; i++) { - _loop_15(i); + _loop_16(i); } proj.rootFiles = filesToKeep; return excludedFiles; @@ -108543,7 +108981,7 @@ var ts; var _this = this; return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { // for now treat files as JavaScript - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); return { referencedFiles: _this.convertFileReferences(result.referencedFiles), importedFiles: _this.convertFileReferences(result.importedFiles), @@ -108578,8 +109016,7 @@ var ts; CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { - var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseJsonText(fileName, text); + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); var normalizedFileName = ts.normalizeSlashes(fileName); var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 630b7a08a28..3cbca96f8fa 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -639,7 +639,7 @@ declare namespace ts { body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; - type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration; + type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | JSDocFunctionType; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; @@ -877,7 +877,7 @@ declare namespace ts { type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; - type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; @@ -1729,6 +1729,16 @@ declare namespace ts { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; + /** Note that the resulting nodes cannot be checked. */ + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName; + /** Note that the resulting nodes cannot be checked. */ + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression; + /** Note that the resulting nodes cannot be checked. */ + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration; + /** Note that the resulting nodes cannot be checked. */ + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; @@ -1748,7 +1758,8 @@ declare namespace ts { getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; + typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; /** * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead * This will be removed in a future version. @@ -1788,33 +1799,79 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + UseOnlyExternalAliasing = 128, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowThisInObjectLiteral = 32768, + AllowQualifedNameInPlaceOfIdentifier = 65536, + AllowAnonymousIdentifier = 131072, + AllowEmptyUnionOrIntersection = 262144, + AllowEmptyTuple = 524288, + AllowUniqueESSymbolType = 1048576, + AllowEmptyIndexInfoType = 2097152, + IgnoreErrors = 3112960, + InObjectTypeLiteral = 4194304, + InTypeAlias = 8388608, + } + enum TypeFormatFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, SuppressAnyReturnType = 256, - WriteTypeParametersInQualifiedName = 512, - AllowThisInObjectLiteral = 1024, - AllowQualifedNameInPlaceOfIdentifier = 2048, - AllowAnonymousIdentifier = 8192, - AllowEmptyUnionOrIntersection = 16384, - AllowEmptyTuple = 32768, - IgnoreErrors = 60416, - InObjectTypeLiteral = 1048576, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowUniqueESSymbolType = 1048576, + AddUndefined = 131072, + WriteArrowStyleSignature = 262144, + InArrayType = 524288, + InElementType = 2097152, + InFirstTypeArgument = 4194304, InTypeAlias = 8388608, + /** @deprecated */ WriteOwnNameForAnyLike = 0, + NodeBuilderFlagsMask = 9469295, } + enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + AllowAnyNodeKind = 4, + } + /** + * @deprecated + */ interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; - buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; + /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; } - interface SymbolWriter { + /** + * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString + */ + interface SymbolWriter extends SymbolTracker { writeKeyword(text: string): void; writeOperator(text: string): void; writePunctuation(text: string): void; @@ -1827,34 +1884,6 @@ declare namespace ts { increaseIndent(): void; decreaseIndent(): void; clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - reportInaccessibleThisError(): void; - reportPrivateInBaseOfClassExpression(propertyName: string): void; - reportInaccessibleUniqueSymbolError(): void; - } - enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 4, - NoTruncation = 8, - WriteArrowStyleSignature = 16, - WriteOwnNameForAnyLike = 32, - WriteTypeArgumentsOfSignature = 64, - InElementType = 128, - UseFullyQualifiedType = 256, - InFirstTypeArgument = 512, - InTypeAlias = 1024, - SuppressAnyReturnType = 4096, - AddUndefined = 8192, - WriteClassExpressionAsTypeLiteral = 16384, - InArrayType = 32768, - UseAliasDefinedOutsideCurrentScope = 65536, - AllowUniqueESSymbolType = 131072, - } - enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, } enum TypePredicateKind { This = 0, @@ -2149,15 +2178,14 @@ declare namespace ts { declaration?: SignatureDeclaration; } enum InferencePriority { - Contravariant = 1, - NakedTypeVariable = 2, - MappedType = 4, - ReturnType = 8, - NeverType = 16, + NakedTypeVariable = 1, + MappedType = 2, + ReturnType = 4, } interface InferenceInfo { typeParameter: TypeParameter; candidates: Type[]; + contraCandidates: Type[]; inferredType: Type; priority: InferencePriority; topLevel: boolean; @@ -2478,6 +2506,7 @@ declare namespace ts { */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string; + createHash?(data: string): string; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2634,6 +2663,10 @@ declare namespace ts { * collisions. */ printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a list of nodes using the given format flags + */ + printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; /** * Prints a source file as-is, without any emit transformations. */ @@ -2689,6 +2722,13 @@ declare namespace ts { interface PrinterOptions { removeComments?: boolean; newLine?: NewLineKind; + omitTrailingSemicolon?: boolean; + } + interface SymbolTracker { + trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + reportInaccessibleThisError?(): void; + reportPrivateInBaseOfClassExpression?(propertyName: string): void; + reportInaccessibleUniqueSymbolError?(): void; } interface TextSpan { start: number; @@ -2701,6 +2741,71 @@ declare namespace ts { interface SyntaxList extends Node { _children: Node[]; } + enum ListFormat { + None = 0, + SingleLine = 0, + MultiLine = 1, + PreserveLines = 2, + LinesMask = 3, + NotDelimited = 0, + BarDelimited = 4, + AmpersandDelimited = 8, + CommaDelimited = 16, + DelimitersMask = 28, + AllowTrailingComma = 32, + Indented = 64, + SpaceBetweenBraces = 128, + SpaceBetweenSiblings = 256, + Braces = 512, + Parenthesis = 1024, + AngleBrackets = 2048, + SquareBrackets = 4096, + BracketsMask = 7680, + OptionalIfUndefined = 8192, + OptionalIfEmpty = 16384, + Optional = 24576, + PreferNewLine = 32768, + NoTrailingNewLine = 65536, + NoInterveningComments = 131072, + NoSpaceIfEmpty = 262144, + SingleElement = 524288, + Modifiers = 131328, + HeritageClauses = 256, + SingleLineTypeLiteralMembers = 448, + MultiLineTypeLiteralMembers = 65, + TupleTypeElements = 336, + UnionTypeConstituents = 260, + IntersectionTypeConstituents = 264, + ObjectBindingPatternElements = 262576, + ArrayBindingPatternElements = 262448, + ObjectLiteralExpressionProperties = 263122, + ArrayLiteralExpressionElements = 4466, + CommaListElements = 272, + CallExpressionArguments = 1296, + NewExpressionArguments = 9488, + TemplateExpressionSpans = 131072, + SingleLineBlockStatements = 384, + MultiLineBlockStatements = 65, + VariableDeclarationList = 272, + SingleLineFunctionBodyStatements = 384, + MultiLineFunctionBodyStatements = 1, + ClassHeritageClauses = 256, + ClassMembers = 65, + InterfaceMembers = 65, + EnumMembers = 81, + CaseBlockClauses = 65, + NamedImportsOrExportsElements = 432, + JsxElementOrFragmentChildren = 131072, + JsxElementAttributes = 131328, + CaseOrDefaultClauseStatements = 81985, + HeritageClauseTypes = 272, + SourceFileStatements = 65537, + Decorators = 24577, + TypeArguments = 26896, + TypeParameters = 26896, + Parameters = 1296, + IndexSignatureParameters = 4432, + } } declare namespace ts { const versionMajorMinor = "2.7"; @@ -2725,26 +2830,14 @@ declare namespace ts { callback: FileWatcherCallback; mtime?: Date; } - /** - * Partial interface of the System thats needed to support the caching of directory structure - */ - interface DirectoryStructureHost { + interface System { + args: string[]; newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string | undefined; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - exit(exitCode?: number): void; - } - interface System extends DirectoryStructureHost { - args: string[]; getFileSize?(path: string): number; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; /** * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that * use native OS file watching @@ -2752,7 +2845,13 @@ declare namespace ts { watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; getExecutingFilePath(): string; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** * This should be cryptographically secure. @@ -2760,6 +2859,7 @@ declare namespace ts { */ createHash?(data: string): string; getMemoryUsage?(): number; + exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; @@ -2812,8 +2912,10 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; @@ -3243,7 +3345,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; - function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; + function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -3711,17 +3813,6 @@ declare namespace ts { declare namespace ts { function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } -declare namespace ts { - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } -} declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -3751,6 +3842,258 @@ declare namespace ts { */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} +declare namespace ts { + type AffectedFileResult = { + result: T; + affected: SourceFile | Program; + } | undefined; + interface BuilderProgramHost { + /** + * return true if file names are treated with case sensitivity + */ + useCaseSensitiveFileNames(): boolean; + /** + * If provided this would be used this hash instead of actual file shape text for detecting changes + */ + createHash?: (data: string) => string; + /** + * When emit or emitNextAffectedFile are called without writeFile, + * this callback if present would be used to write files + */ + writeFile?: WriteFileCallback; + } + /** + * Builder to manage the program state changes + */ + interface BuilderProgram { + /** + * Returns current program + */ + getProgram(): Program; + /** + * Get compiler options of the program + */ + getCompilerOptions(): CompilerOptions; + /** + * Get the source file in the program with file name + */ + getSourceFile(fileName: string): SourceFile | undefined; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Get the diagnostics for compiler options + */ + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics that dont belong to any file + */ + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the syntax diagnostics, for all source files if source file is not supplied + */ + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get all the dependencies of the file + */ + getAllDependencies(sourceFile: SourceFile): ReadonlyArray; + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + /** + * Get the current directory of the program + */ + getCurrentDirectory(): string; + } + /** + * The builder that caches the semantic diagnostics for the program and handles the changed files and affected files + */ + interface SemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Gets the semantic diagnostics from the program for the next affected file and caches it + * Returns undefined if the iteration is complete + */ + getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>; + } + /** + * The builder that can handle the changes in program and iterate through changed file to emit the files + * The semantic diagnostics are cached per file and managed by clearing for the changed/affected files + */ + interface EmitAndSemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult; + } + /** + * Create the builder to manage semantic diagnostics and cache them + */ + function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + /** + * Create the builder that can handle the changes in program and iterate through changed files + * to emit the those files and manage semantic diagnostics cache as well + */ + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + /** + * Creates a builder thats just abstraction over program and can be used with watch + */ + function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram): BuilderProgram; +} +declare namespace ts { + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string) => void; + type CreateProgram = (rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T; + interface WatchCompilerHost { + /** + * Used to create the program when need for program creation or recreation detected + */ + createProgram: CreateProgram; + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string): void; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + createHash?(data: string): string; + /** + * Use to check file presence for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + fileExists(path: string): boolean; + /** + * Use to read file text for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + readFile(path: string, encoding?: string): string | undefined; + /** If provided, used for module resolution as well as to handle directory structure */ + directoryExists?(path: string): boolean; + /** If provided, used in resolutions as well as handling directory structure */ + getDirectories?(path: string): string[]; + /** If provided, used to cache and handle directory structure modifications */ + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + /** Symbol links resolution */ + realpath?(path: string): string; + /** If provided would be used to write log about compilation */ + trace?(s: string): void; + /** If provided is used to get the environment variable */ + getEnvironmentVariable?(name: string): string; + /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + /** + * Host to create watch with root files and options + */ + interface WatchCompilerHostOfFilesAndCompilerOptions extends WatchCompilerHost { + /** root files to use to generate program */ + rootFiles: string[]; + /** Compiler options */ + options: CompilerOptions; + } + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports the diagnostics in reading/writing or parsing of the config file + */ + onConfigFileDiagnostic: DiagnosticReporter; + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Host to create watch with config file + */ + interface WatchCompilerHostOfConfigFile extends WatchCompilerHost, ConfigFileDiagnosticsReporter { + /** Name of the config file to compile */ + configFileName: string; + /** Options to extend */ + optionsToExtend?: CompilerOptions; + /** + * Used to generate source file names from the config file and its include, exclude, files rules + * and also to cache the directory stucture + */ + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + } + interface Watch { + /** Synchronize with host and get updated program */ + getProgram(): T; + } + /** + * Creates the watch what generates program using the config file + */ + interface WatchOfConfigFile extends Watch { + } + /** + * Creates the watch that generates program using the root files and compiler options + */ + interface WatchOfFilesAndCompilerOptions extends Watch { + /** Updates the root files in the program, only if this is not config file compilation */ + updateRootFileNames(fileNames: string[]): void; + } + /** + * Create the watch compiler host for either configFile or fileNames and its options + */ + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + /** + * Creates the watch from the host for root files and compiler options + */ + function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions): WatchOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for config file + */ + function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; +} declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; /** @@ -3985,7 +4328,8 @@ 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; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -4001,6 +4345,10 @@ declare namespace ts { getProgram(): Program; dispose(): void; } + interface CombinedCodeFixScope { + type: "file"; + fileName: string; + } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; includeInsertTextCompletions: boolean; @@ -4078,6 +4426,17 @@ declare namespace ts { */ commands?: CodeActionCommand[]; } + interface CodeFixAction extends CodeAction { + /** + * 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?: {}; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands: ReadonlyArray | undefined; + } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { } @@ -4661,9 +5020,6 @@ declare namespace ts { declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.7"; - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; diff --git a/lib/typescript.js b/lib/typescript.js index c858823e640..4c73d04ba23 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -489,14 +489,19 @@ var ts; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); /*@internal*/ - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + 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"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; (function (TokenFlags) { @@ -570,47 +575,70 @@ var ts; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // empty space 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"; // Error handling - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + 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"; // State - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + 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"; // even though `T` can't be accessed in the current scope. - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; // Write symbols's type argument if it is instantiated symbol - // eg. class C { p: T } <-- Show p as C.p here + // eg. class C { p: T } <-- Show p as C.p here // var a: C; // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; @@ -618,6 +646,8 @@ var ts; // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -904,11 +934,9 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; - InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -1191,6 +1219,8 @@ var ts; 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"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -1208,20 +1238,22 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + 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"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + 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"; // Masks // - Additional bitmasks TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; @@ -1305,6 +1337,78 @@ var ts; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + 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"; + // Whitespace + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + // Brackets/Braces + 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"; + // Other + 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"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "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"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "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 = {})); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1407,7 +1511,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1420,6 +1524,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -1563,6 +1668,9 @@ var ts; ts.forEach = forEach; /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -2220,7 +2328,7 @@ var ts; var result = 0; for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { var v = array_5[_i]; - // Note: we need the following type assertion because of GH #17069 + // TODO: Remove the following type assertion once the fix for #17069 is merged result += v[prop]; } return result; @@ -2727,6 +2835,9 @@ var ts; /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; /** Throws an error because a function is not implemented. */ function notImplemented() { throw new Error("Not implemented"); @@ -3131,7 +3242,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */) + if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) return 3; } // Per RFC 1738 'file' URI schema has the shape file:/// @@ -3908,10 +4019,10 @@ var ts; } function Signature() { } // tslint:disable-line no-empty function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0 /* None */; this.modifierFlagsCache = 0 /* None */; this.transformFlags = 0 /* None */; @@ -4051,9 +4162,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; /** @@ -4172,182 +4281,16 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } // tslint:disable-line no-empty ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - /** - * If the readDirectory result was already cached, it returns that - * Otherwise gets result from host and caches it. - * The host request is done under try catch block to avoid caching incorrect result - */ - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - // If there is exception to read directories, dont cache the result and direct the calls to host - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - // Just clear the cache for now - // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated - clearCache(); - } - else { - // This was earlier a file (hence not in cached directory contents) - // or we never cached the directory containing it - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - // Folder added or removed, clear the cache instead of updating the folder and its structure - clearCache(); - } - else { - // No need to update the directory structure, just files - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } - } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -4626,7 +4569,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -4746,7 +4689,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -5342,6 +5290,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5601,7 +5550,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -5710,6 +5659,7 @@ var ts; Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), 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."), @@ -5819,7 +5769,6 @@ var ts; Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -7713,7 +7662,6 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7736,15 +7684,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: function () { return str += " "; }, @@ -7758,10 +7715,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -7802,6 +7759,12 @@ var ts; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -9206,41 +9169,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 /* EqualsToken */ && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 /* ModuleDeclaration */ && node.body && node.body.kind === 234 /* ModuleDeclaration */ && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -9381,6 +9333,33 @@ var ts; return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208 /* Block */: + case 209 /* VariableStatement */: + case 221 /* WithStatement */: + case 212 /* IfStatement */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 223 /* LabeledStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 225 /* TryStatement */: + case 264 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -10166,7 +10145,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -10806,14 +10797,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0 /* CarriageReturnLineFeed */: return carriageReturnLineFeed; case 1 /* LineFeed */: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; /** @@ -12038,7 +12029,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192 /* AwaitExpression */; + return node.kind === 190 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -12511,7 +12502,7 @@ var ts; /* @internal */ function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. - return ts.isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; // Keywords @@ -13351,8 +13342,8 @@ var ts; case 177 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 161 /* FunctionType */: @@ -18799,7 +18790,6 @@ var ts; scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. - var advanceToken = true; var state = 1 /* SawAsterisk */; var margin = undefined; // + 4 for leading '/** ' @@ -18830,7 +18820,6 @@ var ts; // 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 */` state = 0 /* BeginningOfLine */; - advanceToken = false; margin = undefined; indent++; } @@ -18882,13 +18871,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - t = nextJSDocToken(); - } - else { - advanceToken = true; - t = currentToken; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -18973,7 +18956,8 @@ var ts; // a badly malformed tag should not be added to the list of tags return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -18997,6 +18981,8 @@ var ts; indent = 0; break; case 57 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through case 1 /* EndOfFileToken */: // Done break loop; @@ -19031,7 +19017,7 @@ var ts; } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281 /* JSDocTag */, atToken.pos); @@ -19039,8 +19025,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -19302,34 +19287,44 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 /* Property */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0 /* Property */; + break; case "arg": case "argument": case "param": - return target === 1 /* Parameter */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1 /* Parameter */; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTemplateTag */; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146 /* TypeParameter */); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146 /* TypeParameter */, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -19348,6 +19343,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17 /* OpenBraceToken */); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18 /* CloseBraceToken */); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -22339,6 +22342,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); + case 181 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -22347,15 +22352,19 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } if (subtreeFlags & 524288 /* ContainsSpread */ - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 268435456 /* ContainsSuper */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* ContainsDynamicImport */; @@ -22366,19 +22375,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97 /* SuperKeyword */: - return true; - case 180 /* PropertyAccessExpression */: - case 181 /* ElementAccessExpression */: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97 /* SuperKeyword */; - } - return false; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22391,7 +22388,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22412,7 +22409,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22441,7 +22438,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* ParameterExcludes */; + return transformFlags & ~939525441 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22461,7 +22458,7 @@ var ts; transformFlags |= 1024 /* DestructuringAssignment */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -22487,7 +22484,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. @@ -22504,7 +22501,7 @@ var ts; transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22522,7 +22519,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22533,7 +22530,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537920833 /* CatchClauseExcludes */; + return transformFlags & ~940574017 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -22545,7 +22542,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22559,7 +22556,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* ConstructorExcludes */; + return transformFlags & ~1003668801 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -22586,7 +22583,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22604,7 +22601,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -22615,7 +22612,7 @@ var ts; transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -22659,7 +22656,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22691,7 +22688,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -22716,19 +22713,31 @@ var ts; transformFlags |= 32768 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601249089 /* ArrowFunctionExcludes */; + return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 97 /* SuperKeyword */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (transformFlags & 134217728 /* Super */) { + transformFlags ^= 134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 134217728 /* Super */) { + transformFlags &= ~134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22742,7 +22751,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -22758,7 +22767,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22768,7 +22777,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22777,7 +22786,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22788,7 +22797,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -22797,7 +22806,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~574674241 /* ModuleExcludes */; + return transformFlags & ~977327425 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; @@ -22809,18 +22818,25 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; + return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 536872257 /* NodeExcludes */; + var excludeFlags = 939525441 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 192 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: @@ -22829,8 +22845,6 @@ var ts; case 76 /* ConstKeyword */: case 233 /* EnumDeclaration */: case 268 /* EnumMember */: - case 185 /* TypeAssertionExpression */: - case 203 /* AsExpression */: case 204 /* NonNullExpression */: case 131 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. @@ -22947,7 +22961,8 @@ var ts; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. @@ -22958,11 +22973,11 @@ var ts; if (subtreeFlags & 524288 /* ContainsRest */) { transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 176 /* ArrayBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 177 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; @@ -22975,7 +22990,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; case 179 /* ObjectLiteralExpression */: - excludeFlags = 540087617 /* ObjectLiteralExcludes */; + excludeFlags = 942740801 /* ObjectLiteralExcludes */; if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. @@ -22994,7 +23009,7 @@ var ts; break; case 178 /* ArrayLiteralExpression */: case 183 /* NewExpression */: - excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; if (subtreeFlags & 524288 /* ContainsSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. @@ -23040,27 +23055,27 @@ var ts; case 182 /* CallExpression */: case 183 /* NewExpression */: case 178 /* ArrayLiteralExpression */: - return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; case 234 /* ModuleDeclaration */: - return 574674241 /* ModuleExcludes */; + return 977327425 /* ModuleExcludes */; case 147 /* Parameter */: - return 536872257 /* ParameterExcludes */; + return 939525441 /* ParameterExcludes */; case 188 /* ArrowFunction */: - return 601249089 /* ArrowFunctionExcludes */; + return 1003902273 /* ArrowFunctionExcludes */; case 187 /* FunctionExpression */: case 229 /* FunctionDeclaration */: - return 601281857 /* FunctionExcludes */; + return 1003935041 /* FunctionExcludes */; case 228 /* VariableDeclarationList */: - return 546309441 /* VariableDeclarationListExcludes */; + return 948962625 /* VariableDeclarationListExcludes */; case 230 /* ClassDeclaration */: case 200 /* ClassExpression */: - return 539358529 /* ClassExcludes */; + return 942011713 /* ClassExcludes */; case 153 /* Constructor */: - return 601015617 /* ConstructorExcludes */; + return 1003668801 /* ConstructorExcludes */; case 152 /* MethodDeclaration */: case 154 /* GetAccessor */: case 155 /* SetAccessor */: - return 601015617 /* MethodOrAccessorExcludes */; + return 1003668801 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 133 /* NumberKeyword */: case 130 /* NeverKeyword */: @@ -23079,14 +23094,23 @@ var ts; case 232 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 179 /* ObjectLiteralExpression */: - return 540087617 /* ObjectLiteralExcludes */; + return 942740801 /* ObjectLiteralExcludes */; case 264 /* CatchClause */: - return 537920833 /* CatchClauseExcludes */; + return 940574017 /* CatchClauseExcludes */; case 175 /* ObjectBindingPattern */: case 176 /* ArrayBindingPattern */: - return 537396545 /* BindingPatternExcludes */; + return 940049729 /* BindingPatternExcludes */; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + case 186 /* ParenthesizedExpression */: + case 97 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + return 671089985 /* PropertyAccessExcludes */; default: - return 536872257 /* NodeExcludes */; + return 939525441 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -23926,7 +23950,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -23940,6 +23966,40 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar" }. + */ + function parseNodeModuleFromPath(path) { + path = ts.normalizePath(path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = removeExtensionAndIndex(path.slice(indexAfterPackageName + 1)); + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function removeExtensionAndIndex(path) { + var noExtension = ts.removeFileExtension(path); + return noExtension === "index" ? "" : ts.removeSuffix(noExtension, "/index"); + } /* @internal */ function directoryProbablyExists(directoryName, host) { // if host does not support 'directoryExists' assume that directory will exist @@ -24030,13 +24090,18 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -24194,13 +24259,18 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + /* @internal */ + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -24392,6 +24462,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -24425,10 +24500,25 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { @@ -24525,7 +24615,12 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -24746,14 +24841,13 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. - var _displayBuilder; 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) { @@ -24790,6 +24884,142 @@ var ts; var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + /** + * @deprecated + */ + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896 /* TypeParameters */, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -24805,10 +25035,12 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. - getDiagnostics(sourceFile, cancellationToken); + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -26024,7 +26256,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -26431,6 +26663,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -26558,97 +26794,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 3112960 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 162 /* ConstructorType */ : 161 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 157 /* ConstructSignature */ : 156 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); - } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8 /* NoTruncation */) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256 /* UseFullyQualifiedType */) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096 /* SuppressAnyReturnType */) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1 /* WriteArrayAsGenericType */) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64 /* WriteTypeArgumentsOfSignature */) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; return undefined; @@ -26685,6 +26955,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140 /* UniqueKeyword */, ts.createKeywordTypeNode(137 /* SymbolKeyword */)); } if (type.flags & 2048 /* Void */) { @@ -26706,10 +26981,13 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -26723,7 +27001,7 @@ var ts; // 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 && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + 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); @@ -26736,7 +27014,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } return undefined; @@ -26762,7 +27040,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); @@ -26771,7 +27049,7 @@ var ts; var symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); @@ -26794,10 +27072,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + 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; + } } } else { @@ -26814,7 +27098,8 @@ var ts; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // 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 } } } @@ -26839,11 +27124,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304 /* InObjectTypeLiteral */; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); @@ -26857,7 +27142,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -26871,12 +27156,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -26969,9 +27259,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455 /* Value */); + } + } var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -27018,12 +27323,22 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); @@ -27042,7 +27357,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256 /* SuppressAnyReturnType */) { if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { returnTypeNode = undefined; } @@ -27050,14 +27365,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + 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, 793064 /* Type */, /*expectsIdentifier*/ true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -27068,7 +27386,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -27094,47 +27412,22 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + 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; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216 /* NoAsciiEscaping */); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -27162,11 +27455,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -27229,6 +27604,9 @@ var ts; * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 /* WriteDefaultSymbolWithoutName */ && symbol.escapedName === "default" /* Default */) { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -27238,7 +27616,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } switch (declaration.kind) { @@ -27257,736 +27635,6 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - /** - * Writes only the name of the symbol out to the writer. Uses the original source text - * for the name of the symbol if it is available to match how the user wrote the name. - */ - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - /** - * Writes a property access or element access with the name of the symbol out to the writer. - * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, - * ensuring that any names written with literals use element accesses. - */ - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" /* Default */ ? "default" /* Default */ : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - else { - writePunctuation(writer, 23 /* DotToken */); - writer.writeSymbol(symbolName, symbol); - } - } - /** - * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope - * Meaning needs to be specified if the enclosing declaration is given - */ - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - // Write type arguments of instantiated class/interface here - if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses - // this to determine if an import it has previously seen (and not written out) needs - // to be written to the file once the walk of the tree is complete. - // - // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree - // up front (for example, during checking) could determine if we need to emit the imports - // and we could then access that data during declaration emit. - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if ( - // 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)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - // Get qualified name if the symbol is not a type parameter - // and there is an enclosing declaration or we specifically - // asked for it - var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - var typeFormatFlag = 256 /* UseFullyQualifiedType */ & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, /*endOfChain*/ true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 /* WriteOwnNameForAnyLike */ | 16384 /* WriteClassExpressionAsTypeLiteral */); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024 /* InTypeAlias */; - // Write undefined/null type as any - if (type.flags & 33585807 /* Intrinsic */) { - // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4 /* Reference */) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - // In a literal enum type with a single member E { A }, E and E.A denote the - // same type. We always display this type simply as E. - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 32768 /* TypeParameter */)) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - } - else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && - ((flags & 65536 /* UseAliasDefinedOutsideCurrentScope */) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024 /* UniqueESSymbol */) { - if (flags & 131072 /* AllowUniqueESSymbolType */) { - writeKeyword(writer, 140 /* UniqueKeyword */); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137 /* SymbolKeyword */); - } - else if (type.flags & 96 /* StringOrNumberLiteral */) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288 /* Index */) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128 /* InElementType */); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - else if (type.flags & 1048576 /* IndexedAccess */) { - writeType(type.objectType, 128 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writeType(type.indexType, 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else { - // Should never get here - // { ... } - writePunctuation(writer, 17 /* OpenBraceToken */); - writeSpace(writer); - writePunctuation(writer, 24 /* DotDotDotToken */); - writeSpace(writer); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26 /* CommaToken */) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 128 /* InElementType */); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - if (pos < end) { - writePunctuation(writer, 27 /* LessThanToken */); - writeType(typeArguments[pos], 512 /* InFirstTypeArgument */); - pos++; - while (pos < end) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - writeType(typeArguments[pos], 0 /* None */); - pos++; - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(typeArguments[0], 128 /* InElementType */ | 32768 /* InArrayType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (type.target.objectFlags & 8 /* Tuple */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { - writeAnonymousType(type, flags); - } - else { - // Write the type reference in the format f.g.C where A and B are type arguments - // for outer type parameters, and f and g are the respective declaring containers of those - // type parameters. - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && 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)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23 /* DotToken */); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - if (type.flags & 131072 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); - } - else { - writeTypeList(type.types, 48 /* AmpersandToken */); - } - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - // If type is an anonymous type literal in a type alias declaration, use type alias name - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - else { - // Recursive usage, use any - writeKeyword(writer, 119 /* AnyKeyword */); - } - } - 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 - // However, in case of class expressions, we want to write both the static side and the instance side. - // We skip adding the static side so that the instance side has a chance to be written - // before checking for circular references. - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - // Anonymous types with no symbol are never circular - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || // is exported function symbol - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 4 /* UseTypeOfFunction */) || // use typeof if format flags specify it - ts.contains(symbolStack, symbol); // it is type of the symbol uses itself recursively - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 103 /* TypeOfKeyword */); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455 /* Value */); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216 /* Optional */) { - writePunctuation(writer, 55 /* QuestionToken */); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128 /* InElementType */) { - return true; - } - else if (flags & 512 /* InFirstTypeArgument */) { - // Add parenthesis around function type for the first type argument to avoid ambiguity - var typeParameters = callSignature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writePunctuation(writer, 18 /* CloseBraceToken */); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - var stringIndexInfo = resolved.objectFlags & 2048 /* ReverseMapped */ && resolved.stringIndexInfo ? - createIndexInfo(anyType, resolved.stringIndexInfo.isReadonly, resolved.stringIndexInfo.declaration) : - resolved.stringIndexInfo; - buildIndexSignatureDisplay(stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */) { - if (p.flags & 4194304 /* Prototype */) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = ts.getCheckFlags(p) & 2048 /* ReverseMapped */ ? anyType : getTypeOfSymbol(p); - if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(t, globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92 /* InKeyword */); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - if (type.declaration.questionToken) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85 /* ExtendsKeyword */); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58 /* EqualsToken */); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { - writePunctuation(writer, 17 /* OpenBraceToken */); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26 /* CommaToken */); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177 /* BindingElement */); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - var flags = 512 /* InFirstTypeArgument */; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - flags = 0 /* None */; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19 /* OpenParenToken */); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20 /* CloseParenToken */); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99 /* ThisKeyword */); - } - writeSpace(writer); - writeKeyword(writer, 126 /* IsKeyword */); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { - return; - } - if (flags & 16 /* WriteArrowStyleSignature */) { - writeSpace(writer); - writePunctuation(writer, 36 /* EqualsGreaterThanToken */); - } - else { - writePunctuation(writer, 56 /* ColonToken */); - } - writeSpace(writer); - var typePredicate = getTypePredicateOfSignature(signature); - if (typePredicate) { - buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1 /* Construct */) { - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - } - if (signature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */)) { - // Instantiated signature, write type arguments instead - // This is achieved by passing in the mapper separately - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - switch (kind) { - case 1 /* Number */: - writeKeyword(writer, 133 /* NumberKeyword */); - break; - case 0 /* String */: - writeKeyword(writer, 136 /* StringKeyword */); - break; - } - writePunctuation(writer, 22 /* CloseBracketToken */); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - if (info.type) { - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - } - else { - writeKeyword(writer, 119 /* AnyKeyword */); - } - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } function isDeclarationVisible(node) { if (node) { var links = getNodeLinks(node); @@ -28124,8 +27772,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { resolutionResults[i] = false; } return false; @@ -28159,6 +27807,10 @@ var ts; if (propertyName === 3 /* ResolvedReturnType */) { return target.resolvedReturnType; } + if (propertyName === 4 /* ResolvedBaseConstraint */) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will @@ -28283,7 +27935,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); @@ -29077,7 +28730,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); return type.resolvedBaseTypes = ts.emptyArray; } if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { @@ -29125,7 +28778,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); } } else { @@ -29650,18 +29303,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4 /* Reference */) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144 /* Intersection */) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -30207,12 +29861,17 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0 /* String */)) { + // getIndexedAccessType returns `any` for X[string] where X doesn't have an index signature. + // to avoid this, return `undefined`. + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -30236,29 +29895,30 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216 /* UnionOrIntersection */) { var types = t.types; @@ -30278,7 +29938,7 @@ var ts; return stringType; } if (t.flags & 1048576 /* IndexedAccess */) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -30294,7 +29954,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -30712,7 +30372,7 @@ var ts; // b) It references `arguments` somewhere var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -31006,12 +30666,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -31083,7 +30743,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */); + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) @@ -31629,8 +31289,8 @@ var ts; function getUnionTypePredicate(signatures) { var first; var types = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var sig = signatures_3[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred) { continue; @@ -31912,42 +31572,64 @@ var ts; } return false; } + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // undefined if no transformation is possible. - function getTransformedIndexedAccessType(type) { + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); + 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 + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a + // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen + // 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 getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { // If the index type is generic, or if the object type is generic and doesn't originate in an expression, // we are performing a higher-order index access where we cannot meaningfully access the properties of the @@ -32876,7 +32558,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -33018,8 +32700,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } if (!message) { if (relation === comparableRelation) { @@ -33500,7 +33182,7 @@ var ts; } else if (target.flags & 1048576 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of S. + // A is the constraint of T. var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -33535,7 +33217,7 @@ var ts; } else if (source.flags & 1048576 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. + // A is the constraint of S. var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { @@ -33543,10 +33225,11 @@ var ts; return result; } } - else if (target.flags & 1048576 /* IndexedAccess */ && source.indexType === target.indexType) { - // if we have indexed access types with identical index types, see if relationship holds for - // the two object types. + else if (target.flags & 1048576 /* IndexedAccess */) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -34703,6 +34386,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -34713,6 +34397,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -34739,7 +34424,7 @@ var ts; function isTypeParameterAtTopLevel(type, typeParameter) { return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - /** Create an object with properties named in the string literal type. Every property has type `{}` */ + /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { @@ -34748,7 +34433,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4 /* Property */, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -34800,7 +34485,9 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : emptyObjectType; + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -34819,6 +34506,7 @@ var ts; if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -34887,18 +34575,20 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - // We give lowest priority to inferences of implicitNeverType (which is used as the - // element type for empty array literals). Thus, inferences from empty array literals - // only matter when no other inferences are made. - var p = priority | (source === implicitNeverType ? 16 /* NeverType */ : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -34921,15 +34611,15 @@ var ts; } } else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -34955,7 +34645,7 @@ var ts; // types in contra-variant positions (such as callback parameters). if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2 /* NakedTypeVariable */; + priority |= 1 /* NakedTypeVariable */; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -34999,9 +34689,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -35037,7 +34727,7 @@ var ts; var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4 /* MappedType */; + priority |= 2 /* MappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -35171,10 +34861,19 @@ var ts; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 1 /* Contravariant */ ? getCommonSubtype(baseCandidates) : - context.flags & 1 /* InferUnionTypes */ || inference.priority & 8 /* ReturnType */ ? getUnionType(baseCandidates, 2 /* Subtype */) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + // If we have inferred 'never' but have contravariant candidates. To get a more specific type we + // infer from the contravariant candidates instead. + if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + // We only have contravariant inferences, infer the best common subtype of those + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -35486,16 +35185,6 @@ var ts; return 8388607 /* All */; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576 /* IndexedAccess */) { - // TODO (weswig): This is a substitute for a lazy negated type to remove the types indicated by the TypeFacts from the (potential) union the IndexedAccess refers to - // - See discussion in https://github.com/Microsoft/TypeScript/pull/19275 for details, and test `strictNullNotNullIndexTypeShouldWork` for current behavior - var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; - var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); - if (result !== baseConstraint) { - return result; - } - return type; - } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -36533,17 +36222,18 @@ var ts; var parent = node.parent; return parent.kind === 180 /* PropertyAccessExpression */ || parent.kind === 182 /* CallExpression */ && parent.expression === node || - parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node; + parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 204 /* NonNullExpression */ || + parent.kind === 177 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } - function getDeclaredOrApparentType(symbol, node) { + function getApparentTypeForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - var type = getTypeOfSymbol(symbol); if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } @@ -36622,7 +36312,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */)) { @@ -36872,6 +36562,15 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. @@ -36906,11 +36605,6 @@ var ts; return type; } } - if (noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -37598,7 +37292,7 @@ var ts; // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); + var signatures = getSignaturesOfType(type, 0 /* Call */); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -38248,8 +37942,8 @@ var ts; if (sourceAttributesType) { // Instantiate in context of source type var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); @@ -38943,7 +38637,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -39194,7 +38888,7 @@ var ts; } function isValidMethodAccess(method, type) { var propType = getTypeOfFuncClassEnumModule(method); - var signatures = getSignaturesOfType(propType, 0 /* Call */); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { var thisType = getThisTypeOfSignature(sig); @@ -39369,8 +39063,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var signature = signatures_5[_i]; + 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 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -39505,7 +39199,7 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -39550,7 +39244,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); } } var thisType = getThisTypeOfSignature(signature); @@ -40099,8 +39793,8 @@ var ts; else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -40110,8 +39804,8 @@ var ts; else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var sig = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -41480,6 +41174,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -43093,8 +42790,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_8 = signatures; _a < signatures_8.length; _a++) { - var signature = signatures_8[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -44236,7 +43933,13 @@ var ts; if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + } checkParameterInitializer(node); } return; @@ -44992,7 +44695,8 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -47344,20 +47048,20 @@ var ts; : unknownType; if (type.flags & 1024 /* UniqueESSymbol */ && type.symbol === symbol) { - flags |= 131072 /* AllowUniqueESSymbolType */; + flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 8192 /* AddUndefined */) { + if (flags & 131072 /* AddUndefined */) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -48507,12 +48211,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 /* ArrayBindingPattern */ || node.name.kind === 175 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); @@ -48971,7 +48678,7 @@ var ts; var node = createSynthesizedNode(71 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; - node.autoGenerateKind = 0 /* None */; + node.autoGenerateFlags = 0 /* None */; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -48986,22 +48693,24 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - /** Create a unique temporary variable. */ - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1 /* Auto */; + name.autoGenerateFlags = 1 /* Auto */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + } return name; } ts.createTempVariable = createTempVariable; /** Create a unique temporary variable for use in a loop. */ function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2 /* Loop */; + name.autoGenerateFlags = 2 /* Loop */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -49010,7 +48719,7 @@ var ts; /** Create a unique name based on the supplied text. */ function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3 /* Unique */; + name.autoGenerateFlags = 3 /* Unique */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -49018,10 +48727,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4 /* Node */; + name.autoGenerateFlags = 4 /* Node */; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; + } nextAutoGenerateId++; return name; } @@ -49319,11 +49030,12 @@ var ts; } ts.updateIndexSignature = updateIndexSignature; /* @internal */ - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -52292,7 +52004,9 @@ var ts; // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence - return e.kind === 195 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || + emittedExpression.kind === 293 /* CommaListExpression */ ? ts.createParen(e) : e; } @@ -52942,6 +52656,7 @@ var ts; /// var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -53076,7 +52791,7 @@ var ts; switch (kind) { // Names case 71 /* Identifier */: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145 /* ComputedPropertyName */: @@ -54147,7 +53862,12 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { // If the right-hand value of the destructuring assignment needs to be preserved (as // is the case when the destructuring assignment is part of a larger expression), // then we need to cache the right-hand value. @@ -54191,6 +53911,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -54218,6 +53958,15 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -55303,11 +55052,14 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. @@ -57476,7 +57228,7 @@ var ts; ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -57490,6 +57242,7 @@ var ts; * just-in-time substitution for `super` expressions inside of async methods. */ var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -57527,6 +57280,83 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 215 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 216 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 217 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 264 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 208 /* Block */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 225 /* TryStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 212 /* IfStatement */: + case 221 /* WithStatement */: + case 223 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } /** * Visits an AwaitExpression node. * @@ -57601,6 +57431,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -57613,10 +57510,17 @@ var ts; // `this` and `arguments` objects to `__awaiter`. The generator function // passed to `__awaiter` is executed inside of the callback to the // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -57632,27 +57536,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -57928,8 +57833,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -66088,6 +65993,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. @@ -67321,6 +67227,43 @@ var ts; if (hint === 1 /* Expression */) { return substituteExpression(node); } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 266 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } return node; } /** @@ -68189,9 +68132,9 @@ var ts; * @param tokenStartPos The start pos of the token. * @param emitCallback The callback used to emit the token. */ - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -68200,7 +68143,7 @@ var ts; if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { @@ -68945,9 +68888,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 /* UseTypeOfFunction */ | - 16384 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); + var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 4 /* WriteDefaultSymbolWithoutName */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -68961,7 +68904,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); errorNameNode = undefined; } } @@ -69199,7 +69142,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); write(";"); writeLine(); return tempVarName; @@ -70440,7 +70383,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -70471,7 +70414,6 @@ var ts; /// var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); /*@internal*/ /** @@ -70491,7 +70433,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -70500,7 +70445,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -70633,7 +70581,7 @@ var ts; ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -70699,16 +70647,29 @@ var ts; var generatedNames; // Set of names generated by the NameGenerator. var tempFlagsStack; // Stack of enclosing name generation scopes. var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { // public API printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, // internal API writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -70731,6 +70692,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -70746,6 +70711,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -70773,7 +70748,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -70799,6 +70774,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0 /* Auto */; + reservedNamesStack = []; comments.reset(); setWriter(/*output*/ undefined); } @@ -70862,7 +70838,9 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { @@ -70871,7 +70849,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -71109,7 +71087,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -71133,7 +71111,7 @@ var ts; case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: case 91 /* ImportKeyword */: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; // Expressions case 178 /* ArrayLiteralExpression */: @@ -71229,25 +71207,27 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); } } // // Identifiers // function emitIdentifier(node) { - write(getTextOfNode(node, /*includeTrivia*/ false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names // function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -71259,36 +71239,46 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } // // Signature elements // function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } // @@ -71297,19 +71287,19 @@ var ts; function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -71318,8 +71308,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -71331,13 +71321,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 /* GetAccessor */ ? "get " : "set "); + writeKeyword(node.kind === 154 /* GetAccessor */ ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -71346,34 +71337,37 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } // // Types // function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -71383,7 +71377,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -71405,34 +71401,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336 /* TupleTypeElements */); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260 /* UnionTypeConstituents */); @@ -71441,29 +71442,29 @@ var ts; emitList(node, node.types, 264 /* IntersectionTypeConstituents */); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -71471,23 +71472,24 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); @@ -71496,20 +71498,24 @@ var ts; // Binding patterns // function emitObjectBindingPattern(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); - write("}"); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - write("["); + writePunctuation("["); emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); - write("]"); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Expressions @@ -71546,7 +71552,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -71572,9 +71578,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -71582,26 +71588,27 @@ var ts; emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -71614,30 +71621,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -71661,7 +71672,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; @@ -71670,7 +71681,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -71698,12 +71709,12 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -71716,17 +71727,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } // @@ -71740,13 +71753,13 @@ var ts; // Statements // function emitBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; @@ -71755,27 +71768,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90 /* IfKeyword */, node.pos, node); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, node); + var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, node); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82 /* ElseKeyword */, node.thenStatement.end, node); + writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212 /* IfStatement */) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -71784,55 +71797,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -71846,58 +71867,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77 /* ContinueKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72 /* BreakKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72 /* BreakKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, /*contextNode*/ contextNode); + pos = writeToken(token, pos, writer, /*contextNode*/ contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -71905,24 +71930,26 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos); - write(";"); + writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); + writeSemicolon(); } // // Declarations // function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { @@ -71931,9 +71958,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -71963,19 +71990,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { // We must emit a function body as a single-line body in the following case: @@ -72008,7 +72035,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -72020,7 +72048,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, body); + writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -72045,17 +72073,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -72063,66 +72095,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* HeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* InterfaceMembers */); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81 /* EnumMembers */); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512 /* GlobalAugmentation */) { - write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234 /* ModuleDeclaration */) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(18 /* CloseBraceToken */, node.clauses.end); + writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71 /* Identifier */) { @@ -72134,23 +72177,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -72160,28 +72210,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -72190,14 +72256,16 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } @@ -72205,9 +72273,10 @@ var ts; // Module references // function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } // // JSX @@ -72218,14 +72287,14 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -72233,45 +72302,46 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -72286,13 +72356,15 @@ var ts; // Clauses // function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -72319,25 +72391,25 @@ var ts; } var format = 81985 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 /* MultiLine */ | 64 /* Indented */); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74 /* CatchKeyword */, node.pos); - write(" "); + var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19 /* OpenParenToken */, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } @@ -72346,7 +72418,8 @@ var ts; // function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); // This is to ensure that we emit comment in the following case: // For example: // obj = { @@ -72364,13 +72437,15 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } @@ -72379,7 +72454,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Top-level nodes @@ -72477,33 +72552,60 @@ var ts; // // Helpers // + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328 /* Modifiers */); - write(" "); + writeSpace(); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); - } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); - } - function emitNodeWithPrefix(prefix, node, emit) { + function emitTypeAnnotation(node) { if (node) { - write(prefix); + writePunctuation(":"); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { - write(" "); + writeSpace(); emit(node); } else { @@ -72517,13 +72619,16 @@ var ts; emitList(parentNode, decorators, 24577 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960 /* TypeArguments */); + emitList(parentNode, typeArguments, 26896 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960 /* TypeParameters */); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360 /* Parameters */); + emitList(parentNode, parameters, 1296 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -72543,7 +72648,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); } else { emitParameters(parentNode, parameters); @@ -72558,6 +72663,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -72576,7 +72698,7 @@ var ts; return; } if (format & 7680 /* BracketsMask */) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -72587,7 +72709,7 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { - write(" "); + writeSpace(); } } else { @@ -72599,7 +72721,7 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } // Increase the indent, if requested. if (format & 64 /* Indented */) { @@ -72608,7 +72730,6 @@ var ts; // Emit each child. var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -72619,10 +72740,10 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new @@ -72635,7 +72756,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { - write(" "); + writeSpace(); } } // Emit this child. @@ -72658,7 +72779,7 @@ var ts; // Write a trailing comma, if requested. var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { - write(","); + writePunctuation(","); } // Emit any trailing comment of the last element in the list // i.e @@ -72666,7 +72787,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. @@ -72678,50 +72799,102 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -72912,6 +73085,7 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } /** * Pop the current name generation scope. @@ -72921,15 +73095,22 @@ var ts; return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } /** * Generate the text for a generated identifier. */ function generateName(name) { - if (name.autoGenerateKind === 4 /* Node */) { + 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.skipNameGenerationScope) { + if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { var savedTempFlags = tempFlags; popNameGenerationScope(/*node*/ undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -72959,7 +73140,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } /** * Returns a value indicating whether a name is unique within a container. @@ -72981,11 +73163,14 @@ var ts; * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. */ - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 /* _i */ ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -72998,6 +73183,9 @@ var ts; ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -73090,11 +73278,11 @@ var ts; * Generates a unique identifier for a node. */ function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 3 /* Unique */: return makeUniqueName(ts.idText(name)); } @@ -73112,7 +73300,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 /* Node */ + && node.autoGenerateFlags === 4 /* Node */ && node.autoGenerateId !== autoGenerateId) { break; } @@ -73123,17 +73311,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0 /* None */] = ""; - delimiters[16 /* CommaDelimited */] = ","; - delimiters[4 /* BarDelimited */] = " |"; - delimiters[8 /* AmpersandDelimited */] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28 /* DelimitersMask */]; - } function createBracketsMap() { var brackets = []; brackets[512 /* Braces */] = ["{", "}"]; @@ -73155,474 +73332,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - // Line separators - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - // Delimiters - 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"; - // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - // Brackets/Braces - 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"; - // Other - 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"; - // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "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"] = 256] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "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"] = 26960] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat || (ListFormat = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - function createBuilder(options) { - var isModuleEmit; - var fileInfos = ts.createMap(); - var semanticDiagnosticsPerFile = ts.createMap(); - /** The map has key by source file's path that has been changed */ - var changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - } - hasShapeChanged.clear(); - allFilesExcludingDefaultLibraryFile = undefined; - ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { - // Add new file info - createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, - // Remove existing file info - onDeleteValue: removeExistingFileInfo, - // We will update in place instead of deleting existing value and adding new one - onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } - }); - } - function registerChangedFile(path) { - changedFilesSet.set(path, true); - // All changed files need to re-evaluate its semantic diagnostics - semanticDiagnosticsPerFile.delete(path); - } - function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - function removeExistingFileInfo(_existingFileInfo, path) { - // Since we dont need to track removed file as changed file - // We can just remove its diagnostics - changedFilesSet.delete(path); - semanticDiagnosticsPerFile.delete(path); - emitHandler.onRemoveSourceFile(path); - } - function updateExistingFileInfo(program, existingInfo, sourceFile) { - if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - var compilerOptions = program.getCompilerOptions(); - if (!changedFilesSet.size) { - return ts.emptyArray; - } - // With --out or --outFile all outputs go into single file, do it only once - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - changedFilesSet.clear(); - return [program.emit(/*targetSourceFile*/ undefined, writeFileCallback)]; - } - var seenFiles = ts.createMap(); - var result; - changedFilesSet.forEach(function (_true, path) { - // Get the affected Files by this program - var affectedFiles = getFilesAffectedBy(program, path); - affectedFiles.forEach(function (affectedFile) { - // Affected files shouldnt have cached diagnostics - semanticDiagnosticsPerFile.delete(affectedFile.path); - if (!seenFiles.has(affectedFile.path)) { - seenFiles.set(affectedFile.path, true); - // Emit the affected file - (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - ts.Debug.assert(changedFilesSet.size === 0); - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - // We dont need to cache the diagnostics just return them from program - return program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken); - } - var diagnostics; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); - } - return diagnostics || ts.emptyArray; - } - function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; - } - // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, diagnostics); - return diagnostics; - } - function clear() { - isModuleEmit = undefined; - emitHandler = undefined; - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - /** - * For script files that contains only ambient external modules, although they are not actually external module files, - * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, - * there are no point to rebuild all script files if these special files have changed. However, if any statement - * in the file is not ambient external module, we treat it as a regular script file. - */ - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - /** - * @return {boolean} indicates if the shape signature has changed since last update. - */ - function updateShapeSignature(program, sourceFile) { - ts.Debug.assert(!!sourceFile); - // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (hasShapeChanged.has(sourceFile.path)) { - return false; - } - hasShapeChanged.set(sourceFile.path, true); - var info = fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); - var prevSignature = info.signature; - var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - /** - * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true - */ - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - // We need to use a set here since the code can contain the same import twice, - // but that will only be one dependency. - // To avoid invernal conversion, the key of the referencedFiles map must be of type Path - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - // Handle triple slash references - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - // Handle type reference directives - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - /** - * Gets all files of the program excluding the default library file - */ - function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { - // Use cached result - if (allFilesExcludingDefaultLibraryFile) { - return allFilesExcludingDefaultLibraryFile; - } - var result; - addSourceFile(firstSourceFile); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - if (sourceFile !== firstSourceFile) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function getFilesAffectedByUpdatedShape(program, sourceFile) { - var options = program.getCompilerOptions(); - // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, - // so returning the file itself is good enough. - if (options && (options.out || options.outFile)) { - return [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - // Changed if we had references - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - // If there are any new references that werent present previously there is change - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - // Otherwise its changed if there are more references previously than now - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - // Remove existing references - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - // add files referencing the removedFilePath, as changed files too - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - // Delete the entry for the removed file path - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.arrayFrom(ts.mapDefinedIterator(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - })); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return [sourceFile]; - } - // Now we need to if each file in the referencedBy list has a shape change as well. - // Because if so, its own referencedBy files need to be saved as well to make the - // emitting result consistent with files on disk. - var seenFileNamesMap = ts.createMap(); - // Start with the paths this file was referenced by - var path = sourceFile.path; - seenFileNamesMap.set(path, sourceFile); - var queue = getReferencedByPaths(path); - while (queue.length > 0) { - var currentPath = queue.pop(); - if (!seenFileNamesMap.has(currentPath)) { - var currentSourceFile = program.getSourceFileByPath(currentPath); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - // Return array of values that needs emit - return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); - } - } - } - ts.createBuilder = createBuilder; })(ts || (ts = {})); /// /// /// -/// var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; @@ -73853,9 +73566,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = 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_5), lastLine = _b.line, lastLineChar = _b.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 hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -74184,7 +73897,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -74594,24 +74308,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - // If the noEmitOnError flag is set, then check if we have any errors so far. If so, - // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we - // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } // Create the emit resolver outside of the "emitTime" tracking code below. That way @@ -74622,7 +74338,7 @@ var ts; // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -75175,7 +74891,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. @@ -75641,6 +75357,19 @@ var ts; hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + return ts.forEachEmittedFile(getEmitHost(), function (_a) { + var jsFilePath = _a.jsFilePath, declarationFilePath = _a.declarationFilePath; + return isSameFile(jsFilePath, file) || + (declarationFilePath && isSameFile(declarationFilePath, file)); + }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } } ts.createProgram = createProgram; /* @internal */ @@ -75688,6 +75417,2168 @@ var ts; return res; } })(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + 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) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + 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) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + if (map1 === undefined) { + return map2 === undefined; + } + if (map2 === undefined) { + return map1 === undefined; + } + // Has same size and every key is present in both maps + return map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState && oldState.referencedMap; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var affectedFilesIndex = state.affectedFilesIndex; + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + semanticDiagnosticsPerFile.delete(affectedFile.path); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + state.currentChangedFilePath = nextKey.value; + state.semanticDiagnosticsPerFile.delete(nextKey.value); + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var host; + var newProgram; + if (ts.isArray(newProgramOrRootNames)) { + newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram()); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program) { + newProgram = undefined; + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = void 0; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + 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)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + 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)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * Updates the existing wild card directory watches with the new set of wild card directories from the config file + * after new program is created because the config file was reloaded or program was created first time from the config file + * Note that there is no need to call this function when the program is updated with additional files without reloading config files, + * as wildcard directories wont change unless reloading config file + */ + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + function addFileWatcher(host, file, cb) { + return host.watchFile(file, cb); + } + ts.addFileWatcher = addFileWatcher; + function addFileWatcherWithLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb); + } + ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; + function addFilePathWatcher(host, file, cb, path) { + return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); + } + ts.addFilePathWatcher = addFilePathWatcher; + function addFilePathWatcherWithLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb, path); + } + ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; + function addDirectoryWatcher(host, directory, cb, flags) { + var recursive = (flags & 1 /* Recursive */) !== 0; + return host.watchDirectory(directory, cb, recursive); + } + ts.addDirectoryWatcher = addDirectoryWatcher; + function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { + var info = "PathInfo: " + file; + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } + var watcher = addWatch(host, file, function (fileName, cbOptional1) { + var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; + log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); + var start = ts.timestamp(); + cb(fileName, cbOptional1, optional); + var elapsed = ts.timestamp() - start; + log(watcherCaption + "Elapsed: " + elapsed + "ms Trigger: " + fileName + optionalInfo + " " + info); + }, optional); + return { + close: function () { + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); + } + watcher.close(); + } + }; + } + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var allFilesHaveInvalidatedResolution = false; + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createMap(); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = rootDir && resolutionHost.toPath(rootDir); + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return collected && collected.has(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + clearPerDirectoryResolutions(); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + if (resolution.failedLookupLocations) { + if (existingResolution && existingResolution.failedLookupLocations) { + watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution); + } + else { + watchFailedLookupLocationOfResolution(resolution, 0); + } + } + else if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution || oldResolution.isInvalidated) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { + for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + // Folder isnt at expected minimun levels + return false; + } + } + return true; + } + function canWatchDirectory(dirPath) { + return isDirectoryAtleastAtLevelFromFSRoot(dirPath, + // When root is "/" do not watch directories like: + // "/", "/user", "/user/username", "/user/username/folderAtRoot" + // When root is "c:/" do not watch directories like: + // "c:/", "c:/folderAtRoot" + dirPath.charCodeAt(0) === 47 /* slash */ ? 3 : 1); + } + function filterFSRootDirectoriesToWatch(watchPath, dirPath) { + if (!canWatchDirectory(dirPath)) { + watchPath.ignore = true; + } + return watchPath; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + return { dir: rootDir, dirPath: rootPath }; + } + var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); + var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch + if (isNodeModulesDirectory(dirPath)) { + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + } + // Use some ancestor of the root directory + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) { + var failedLookupLocations = resolution.failedLookupLocations; + var existingFailedLookupLocations = existingResolution.failedLookupLocations; + for (var index = 0; index < failedLookupLocations.length; index++) { + if (index === existingFailedLookupLocations.length) { + // Additional failed lookup locations, watch from this index + watchFailedLookupLocationOfResolution(resolution, index); + return; + } + else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) { + // Different failed lookup locations, + // Watch new resolution failed lookup locations from this index and + // stop watching existing resolutions from this index + watchFailedLookupLocationOfResolution(resolution, index); + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index); + return; + } + } + // All new failed lookup locations are already watched (and are same), + // Stop watching failed lookup locations of existing resolution after failed lookup locations length + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length); + } + function watchFailedLookupLocationOfResolution(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + } + } + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (resolution.failedLookupLocations) { + stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0); + } + } + function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; + } + } + } + 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 + 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) { + if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + } + }, 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + }); + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function createTypeRootsWatch(_typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existance changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; + } + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + /** + * Use this function to return if directory exists to get type roots to watch + * If we return directory exists then only the paths will be added to type roots + * Hence return true for all directories except root directories which are filtered from watching + */ + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; + /** + * Create a function that reports error by writing to the system and handles the formating of the diagnostic + */ + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + function clearScreenIfNotWatchingForFileChanges(system, diagnostic) { + if (system.clearScreen && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + system.clearScreen(); + } + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + /** Parses config file using System interface */ + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = parseConfigFile(configFileName, optionsToExtend, host); + host.onConfigFileDiagnostic = undefined; + 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 parseConfigFile(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); + result.parseDiagnostics.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + var cwd = host.getCurrentDirectory(); + var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + configParseResult.errors.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + return configParseResult; + } + ts.parseConfigFile = parseConfigFile; + /** + * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options + */ + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName) { + // First get and report any syntactic errors. + var diagnostics = program.getSyntacticDiagnostics().slice(); + var reportSemanticDiagnostics = false; + // If we didn't have any syntactic errors, then also try getting the global and + // semantic errors. + if (diagnostics.length === 0) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === 0) { + reportSemanticDiagnostics = true; + } + } + // Emit and report any errors we ran into. + var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } + } + if (emitSkipped && diagnostics.length > 0) { + // If the emitter didn't emit anything, then pass that value along. + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + // The emitter emitted something, inform the caller if that happened in the presence + // of diagnostics or not. + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + 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 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); }, + onWatchStatusChange: reportWatchStatus || createWatchStatusReporter(system), + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName); + } + } + /** + * Report error and exit + */ + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + /** + * Creates the watch compiler host from system for config file in watch mode + */ + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + /** + * Creates the watch compiler host from system for compiling root files and options in watch mode + */ + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + var missingFilesMap; // Map of file watchers for the missing files + var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file + var timerToUpdateProgram; // timer callback to recompile the program + var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info + var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files + var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, configFileSpecs = host.configFileSpecs, configFileWildCardDirectories = host.configFileWildCardDirectories; + var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onConfigFileDiagnostic: host.onConfigFileDiagnostic, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + }; + // From tsc we want to get already parsed result and hence check for rootFileNames + if (configFileName && !rootFileNames) { + parseConfigFile(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); + var writeLog = loggingEnabled ? trace : ts.noop; + var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; + var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; + var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, writeLog); + } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var newLine = updateNewLine(); + var compilerHost = { + // Members for CompilerHost + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + // Members for ResolutionCacheHost + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: watchDirectory, + watchTypeRootsDirectory: watchDirectory, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog + }; + // Cache for the module resolution + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, + /*logChangesWhenResolvingModule*/ false); + // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : + (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : + (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + // All resolutions are invalid if user provided resolutions + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + return builderProgram; + } + // Compile the program + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram); + resolutionCache.finishCachingPerDirectoryResolution(); + // Update watches + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + // These are the paths that program creater told us as not in use any more but were missing on the disk. + // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO, + // if there is already watcher for it (for missing files) + // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed + // so that at later time we have correct result of their presence + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + reportWatchDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes); + return builderProgram; + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function fileExists(fileName) { + var path = toPath(fileName); + var hostSourceFileInfo = sourceFilesCache.get(path); + if (hostSourceFileInfo !== undefined) { + return !ts.isString(hostSourceFileInfo); + } + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + // No source file on the host + if (ts.isString(hostSourceFile)) { + return undefined; + } + // Create new source file if requested or the versions dont match + if (!hostSourceFile || shouldCreateNewSourceFile || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + } + } + else { + // There is no source file on host any more, close the watch, missing file paths will track it + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, hostSourceFile.version.toString()); + } + } + else { + var fileWatcher = void 0; + if (sourceFile) { + sourceFile.version = "1"; + fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: 1, fileWatcher: fileWatcher }); + } + else { + sourceFilesCache.set(path, "0"); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + } + } + function removeSourceFile(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + resolutionCache.invalidateResolutionOfFile(path); + } + sourceFilesCache.delete(path); + } + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || ts.isString(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + // If this is the source file thats in the cache and new program doesnt need it, + // remove the cached entry. + // Note we arent deleting entry if file became missing in new program or + // there was version update and new source file was created. + if (hostSourceFileInfo) { + // record the missing file paths so they can be removed later if watchers arent tracking them + if (ts.isString(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + sourceFilesCache.delete(oldSourceFile.path); + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine); + } + } + // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch + // operations (such as saving all modified files in an editor) a chance to complete before we kick + // off a new compilation. + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + timerToUpdateProgram = host.setTimeout(updateProgram, 250); + } + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); + } + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; + } + } + function reloadFileNamesFromConfigFile() { + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { + host.onConfigFileDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + rootFileNames = result.fileNames; + // Update the program + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + var configParseResult = ts.parseConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); + rootFileNames = configParseResult.fileNames; + compilerOptions = configParseResult.options; + configFileSpecs = configParseResult.configFileSpecs; + configFileWildCardDirectories = configParseResult.wildcardDirectories; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile) { + // Update the cache + if (eventKind === ts.FileWatcherEventKind.Deleted) { + resolutionCache.invalidateResolutionOfFile(path); + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, (++hostSourceFile.version).toString()); + } + } + else { + // Deleted file created + if (ts.isString(hostSourceFile)) { + sourceFilesCache.delete(path); + } + else { + // file changed - just update the version + hostSourceFile.version++; + } + } + } + // Update the program + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchDirectory(directory, cb, flags) { + return watchDirectoryWorker(host, directory, cb, flags, writeLog); + } + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, missingFilePath, writeLog); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + // Delete the entry in the source files cache so that new source file is created + removeSourceFile(missingFilePath); + // When a missing file is created, we should update the graph. + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + if (configFileWildCardDirectories) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory(directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existance changed, update the sourceFiles cache + var result = cachedDirectoryStructureHost && cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + // Instead of deleting the file, mark it as changed instead + // Many times node calls add/remove/file when watching directories recursively + var hostSourceFile = sourceFilesCache.get(fileOrDirectoryPath); + if (hostSourceFile && !ts.isString(hostSourceFile) && (result ? result.fileExists : directoryStructureHost.fileExists(fileOrDirectory))) { + hostSourceFile.version++; + } + else { + removeSourceFile(fileOrDirectoryPath); + } + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createWatchProgram = createWatchProgram; +})(ts || (ts = {})); /// /// /// @@ -75840,7 +77731,7 @@ var ts; }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -78711,8 +80602,8 @@ var ts; } } ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); @@ -78965,6 +80856,18 @@ var ts; return true; } ts.addToSeen = addToSeen; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -78979,6 +80882,7 @@ var ts; var lineStart; var indent; resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { displayParts: function () { return displayParts; }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, @@ -78988,8 +80892,18 @@ var ts; writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeSymbol: writeSymbol, writeLine: writeLine, + write: unknownWrite, + writeTextOfNode: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, @@ -79110,14 +81024,17 @@ var ts; /** * The default is CRLF. */ - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; } ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; function lineBreakPart() { return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; + /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -79130,20 +81047,20 @@ var ts; ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - flags |= 65536 /* UseAliasDefinedOutsideCurrentScope */; + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); }); } ts.signatureToDisplayParts = signatureToDisplayParts; @@ -79504,7 +81421,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -79513,8 +81430,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -79837,32 +81754,39 @@ var ts; if (!ts.isTrivia(kind)) { return start; } - // Don't bother with newlines/whitespace. - if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { - continue; - } - // Only bother with the trivia if it at least intersects the span of interest. - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - // Classifying a comment might cause us to reuse the trivia scanner - // (because of jsdoc comments). So after we classify the comment make - // sure we set the scanner position back to where it needs to be. - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - pushClassification(start, width, 1 /* comment */); + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. continue; - } - // for the ||||||| and ======== markers, add a comment for the first line, - // and then lex all subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); - classifyDisabledMergeCode(text, start, end); + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); } } } @@ -80403,10 +82327,12 @@ var ts; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options + var seen = ts.createMap(); if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + var typesName = _a[_i]; + var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + pushResult(moduleName); } } else if (host.getDirectories) { @@ -80418,31 +82344,38 @@ var ts; if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(host, root, span, result); + getCompletionEntriesFromDirectories(root); } } - } - if (host.getDirectories) { // Also get all @types typings installed in visible node_modules directories for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, typesDir, span, result); + getCompletionEntriesFromDirectories(typesDir); } } return result; - } - function getCompletionEntriesFromDirectories(host, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); + function getCompletionEntriesFromDirectories(directory) { + ts.Debug.assert(!!host.getDirectories); + if (tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + var directoryName = ts.getBaseFileName(typeDirectory); + var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + pushResult(moduleName); + } } } } + function pushResult(moduleName) { + if (!seen.has(moduleName)) { + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + seen.set(moduleName, true); + } + } } function findPackageJsons(directory, host) { var paths = []; @@ -80580,16 +82513,19 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; // Keywords at function like body })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && pathCompletionsInfo(entries); } - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); - } var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteral(contextToken) && !ts.isNoSubstitutionTemplateLiteral(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host, log); + } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); @@ -80688,10 +82624,19 @@ var ts; return undefined; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - ts.Debug.assert(!(needsConvertPropertyAccess && !propertyAccessToConvert)); if (needsConvertPropertyAccess && !includeInsertTextCompletions) { return undefined; } + var insertText; + var replacementSpan; + if (kind === 1 /* Global */ && origin && origin.type === "this-type") { + insertText = needsConvertPropertyAccess ? "this[\"" + name + "\"]" : "this." + name; + } + else if (needsConvertPropertyAccess) { + // TODO: GH#20619 Use configured quote style + insertText = "[\"" + name + "\"]"; + replacementSpan = ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end); + } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but // really we should consider passing the meaning for the node so that we don't report @@ -80705,13 +82650,10 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - // TODO: GH#20619 Use configured quote style - insertText: needsConvertPropertyAccess ? "[\"" + name + "\"]" : undefined, - replacementSpan: needsConvertPropertyAccess - ? ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end) - : undefined, - hasAction: trueOrUndefined(needsConvertPropertyAccess || origin !== undefined), + hasAction: trueOrUndefined(!!origin && origin.type === "export"), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, }; } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { @@ -80722,7 +82664,7 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && ts.stripQuotes(origin.moduleSymbol.name); + return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); @@ -80757,68 +82699,81 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } } - function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || !ts.isStringLiteral(node) && !ts.isNoSubstitutionTemplateLiteral(node)) { - return undefined; - } - if (node.parent.kind === 265 /* PropertyAssignment */ && - node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && - node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - var type = typeChecker.getTypeAtLocation(node.parent.expression); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); - } - else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ - || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) - || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker); - return pathCompletionsInfo(entries); - } - else if (ts.isIndexedAccessTypeNode(node.parent.parent)) { - // Get all apparent property names - // i.e. interface Foo { - // foo: string; - // bar: string; - // } - // let x: Foo["/*completion position*/"] - var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); - } - else { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, log) { + switch (node.parent.kind) { + case 174 /* LiteralType */: + switch (node.parent.parent.kind) { + case 160 /* TypeReference */: + // TODO: GH#21168 + return undefined; + case 172 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + default: + return undefined; + } + case 265 /* PropertyAssignment */: + if (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && + node.parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); + } + return fromContextualType(); + case 181 /* ElementAccessExpression */: { + var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + var type = typeChecker.getTypeAtLocation(expression); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + } + break; } + case 182 /* CallExpression */: + case 183 /* NewExpression */: + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: + case 249 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return pathCompletionsInfo(Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker)); + default: + return fromContextualType(); + } + function fromContextualType() { // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" return getStringLiteralCompletionEntriesFromType(getContextualTypeFromParent(node, typeChecker), typeChecker); @@ -80951,7 +82906,7 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -81004,7 +82959,7 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo + return symbolOriginInfo && symbolOriginInfo.type === "export" ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) : { codeActions: undefined, sourceDisplay: undefined }; } @@ -81018,7 +82973,6 @@ var ts; host: host, program: program, checker: checker, - newLineCharacter: host.getNewLine(), compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, @@ -81389,6 +83343,9 @@ var ts; keywordFilters = 2 /* ConstructorParameterKeywords */; return true; } + if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { + keywordFilters = 3 /* FunctionLikeBodyKeywords */; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { // cursor inside class declaration getGetClassLikeCompletionSymbols(classLikeContainer); @@ -81447,6 +83404,17 @@ var ts; } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (options.includeInsertTextCompletions && scopeNode.kind !== 269 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbols.push(symbol); + } + } + } if (options.includeExternalModuleExports) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } @@ -81534,7 +83502,7 @@ var ts; // Don't add a completion for a re-export, only for the original. // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + if (typeChecker.getMergedSymbol(symbol.parent) !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } @@ -81542,10 +83510,10 @@ var ts; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - var origin = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; if (stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; } } }); @@ -81924,6 +83892,21 @@ var ts; } return undefined; } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + }); + return container && container; + } + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -82270,13 +84253,13 @@ var ts; return validIdentiferResult; switch (kind) { case 5 /* None */: - case 1 /* Global */: case 3 /* MemberLike */: return undefined; case 0 /* ObjectPropertyDeclaration */: // TODO: GH#18169 return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2 /* PropertyAccess */: + case 1 /* Global */: // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; case 4 /* String */: @@ -82301,6 +84284,8 @@ var ts; return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); case 2 /* ConstructorParameterKeywords */: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + case 3 /* FunctionLikeBodyKeywords */: + return getFilteredKeywordCompletions(isFunctionLikeBodyCompletionKeywordText); default: ts.Debug.assertNever(keywordFilter); } @@ -82354,6 +84339,24 @@ var ts; function isConstructorParameterCompletionKeywordText(text) { return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); } + function isFunctionLikeBodyCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 123 /* ConstructorKeyword */: + case 115 /* StaticKeyword */: + case 117 /* AbstractKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + return false; + } + return true; + } + function isFunctionLikeBodyCompletionKeywordText(text) { + return isFunctionLikeBodyCompletionKeyword(ts.stringToToken(text)); + } function isEqualityOperatorKind(kind) { switch (kind) { case 34 /* EqualsEqualsEqualsToken */: @@ -83859,7 +85862,7 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifier(symbol, node, checker); + symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker); // Compute the meaning from the location and the symbol it references var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; @@ -83902,7 +85905,7 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifier(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { var parent = node.parent; if (ts.isExportSpecifier(parent)) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); @@ -83911,7 +85914,12 @@ var ts; // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. return checker.getImmediateAliasedSymbol(symbol); } - return symbol; + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }) || symbol; } var SpecialSearchKind; (function (SpecialSearchKind) { @@ -83925,8 +85933,8 @@ var ts; */ var State = /** @class */ (function () { function State(sourceFiles, - /** True if we're searching for constructor references. */ - specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; this.specialSearchKind = specialSearchKind; this.checker = checker; @@ -85240,26 +87248,14 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); if (!type) { return undefined; } if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_5 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(/*to*/ result_5, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); - } - }); - return result_5; + return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(typeChecker, type.symbol, node); + return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function getDefinitionAndBoundSpan(program, sourceFile, position) { @@ -85303,59 +87299,29 @@ var ts; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var result = []; - var declarations = symbol.getDeclarations(); var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - // Just add all the declarations. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (ts.isNewExpressionTarget(location) || location.kind === 123 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - // Find the first class-like declaration and try to get the construct signature. - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } + if (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */ && symbol.flags & 32 /* Class */) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } - return false; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); - } - return false; + function getCallSignatureDefinition() { + return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + function getSignatureDefinition(signatureDeclarations, selectConstructors) { if (!signatureDeclarations) { - return false; + return undefined; } - var declarations = []; - var definition; - for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { - var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 153 /* Constructor */ : isSignatureDeclaration(d)) { - declarations.push(d); - if (d.body) - definition = d; - } - } - if (declarations.length) { - result.push(createDefinitionInfo(definition || ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; - } - return false; + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + : undefined; } } function isSignatureDeclaration(node) { @@ -85497,18 +87463,29 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - ts.forEach(ts.getAllJSDocs(declaration), function (doc) { - if (doc.comment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(ts.textPart(doc.comment)); + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); } - }); + documentationComment.push(ts.textPart(comment)); + } }); return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 289 /* JSDocPropertyTag */: + return [declaration]; + case 288 /* JSDocTypedefTag */: + return [declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; @@ -85539,10 +87516,13 @@ var ts; return comment; } function withNode(node) { - return node.getText() + " " + comment; + return addComment(node.getText()); } function withList(list) { - return list.map(function (x) { return x.getText(); }) + " " + comment; + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; } } /** @@ -85955,8 +87935,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_6.config; + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.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. @@ -88321,6 +90301,7 @@ var ts; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); + var printer = ts.createPrinter({ removeComments: true }); var items = ts.map(candidates, function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; @@ -88336,14 +90317,20 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); } else { isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + } }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -88351,7 +90338,15 @@ var ts; suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + } + else { + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + } }); ts.addRange(suffixDisplayParts, returnTypeParts); return { @@ -88372,7 +90367,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: parameter.name, @@ -88383,7 +90379,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation); + var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: typeParameter.symbol.name, @@ -88518,6 +90515,7 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; + var printer; var documentationFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { @@ -88586,14 +90584,14 @@ var ts; displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -88665,7 +90663,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); @@ -88714,7 +90712,7 @@ var ts; else if (declaration.kind !== 156 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter @@ -88823,7 +90821,8 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -88878,6 +90877,12 @@ var ts; documentation = documentationFromAlias; } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); @@ -88899,7 +90904,7 @@ var ts; if (alias && symbolToDisplay === symbol) { symbolToDisplay = alias; } - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { @@ -88929,7 +90934,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -88944,7 +90949,8 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -90479,29 +92485,32 @@ var ts; return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var indentation = inheritedIndentation; var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta - indentation = startLine === lastIndentedLine - ? indentationOnLastIndentedLine - : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; } - else if (indentation === -1 /* Unknown */) { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; } } - return { - indentation: indentation, - delta: delta - }; + else { + return { indentation: inheritedIndentation, delta: delta }; + } } function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { @@ -90535,67 +92544,55 @@ var ts; case 18 /* CloseBraceToken */: case 22 /* CloseBracketToken */: case 20 /* CloseParenToken */: - return indentation + getEffectiveDelta(delta, container); + return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind, container) { - if (nodeStartLine !== line && node.decorators) { - if (kind === getFirstNonDecoratorTokenOfNode(node)) { - // if this token is the first token following the list of decorators, we do not need to indent - return indentation; - } - } - switch (kind) { - // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: - return indentation; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: { - if (container.kind === 252 /* JsxOpeningElement */ || - container.kind === 253 /* JsxClosingElement */ || - container.kind === 251 /* JsxSelfClosingElement */) { - return indentation; - } - break; - } - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: { - if (container.kind !== 173 /* MappedType */) { - return indentation; - } - break; - } - } - // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; + return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, - getDelta: function (child) { return getEffectiveDelta(delta, child); }, + getDelta: getDelta, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { - if (lineAdded) { - indentation += options.indentSize; - } - else { - indentation -= options.indentSize; - } - if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; - } - else { - delta = 0; - } + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; } } }; - function getEffectiveDelta(delta, child) { + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 17 /* OpenBraceToken */: + case 18 /* CloseBraceToken */: + case 19 /* OpenParenToken */: + case 20 /* CloseParenToken */: + case 82 /* ElseKeyword */: + case 106 /* WhileKeyword */: + case 57 /* AtToken */: + return false; + case 41 /* SlashToken */: + case 29 /* GreaterThanToken */: + switch (container.kind) { + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: + return false; + } + break; + case 21 /* OpenBracketToken */: + case 22 /* CloseBracketToken */: + if (container.kind !== 173 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0; } @@ -90618,7 +92615,7 @@ var ts; // context node is set to parent of the token after processing every token var childContextNode = contextNode; // if there are any tokens that logically belong to node and interleave child nodes - // such tokens will be consumed in processChildNode for for the child that follows them + // such tokens will be consumed in processChildNode for the child that follows them ts.forEachChild(node, function (child) { processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, function (nodes) { @@ -90840,23 +92837,25 @@ var ts; var trimTrailingWhitespaces; var lineAction = 0 /* None */; if (rule) { - applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { - lineAction = 2 /* LineRemoved */; - // Handle the case where the next line is moved to be the end of this line. - // In this case we don't indent the next line in the next pass. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); - } - } - else if (rule.action & 4 /* NewLine */ && currentStartLine === previousStartLine) { - lineAction = 1 /* LineAdded */; - // Handle the case where token2 is moved to the new line. - // In this case we indent token2 in the next pass but we set - // sameLineIndent flag to notify the indenter that the indentation is within the line. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); - } + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; @@ -91004,14 +93003,16 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; switch (rule.action) { case 1 /* Ignore */: // no action required - return; + return 0 /* None */; case 8 /* Delete */: if (previousRange.end !== currentRange.pos) { // delete characters starting from t1.end up to t2.pos exclusive recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } break; case 4 /* NewLine */: @@ -91019,25 +93020,27 @@ var ts; // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; } break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } - break; } + return 0 /* None */; } } var LineAction; @@ -91050,7 +93053,7 @@ var ts; * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword - tokenAtPosition, predicate) { + tokenAtPosition, predicate) { if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { @@ -91149,12 +93152,12 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; } - return spaces ? tabString + repeat(" ", spaces) : tabString; + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; } else { var spacesString = void 0; @@ -91164,20 +93167,13 @@ var ts; internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = ts.repeatString(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { spacesString = internedSpacesIndentation[quotient]; } - return remainder ? spacesString + repeat(" ", remainder) : spacesString; - } - function repeat(value, count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += value; - } - return s; + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; } } formatting.getIndentationString = getIndentationString; @@ -91842,7 +93838,7 @@ var ts; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options) === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); }; ChangeTracker.with = function (context, cb) { var tracker = ChangeTracker.fromContext(context); @@ -92397,6 +94393,38 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeTextOfNode = function (text, node) { this.writer.writeTextOfNode(text, node); }; @@ -92435,8 +94463,8 @@ var ts; Writer.prototype.isAtStartOfLine = function () { return this.writer.isAtStartOfLine(); }; - Writer.prototype.reset = function () { - this.writer.reset(); + Writer.prototype.clear = function () { + this.writer.clear(); this.lastNonTriviaPosition = 0; }; return Writer; @@ -92580,8 +94608,9 @@ var ts; // A map with the refactor code as key, the refactor itself as value // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want var refactors = ts.createMap(); - function registerRefactor(refactor) { - refactors.set(refactor.name, refactor); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { @@ -93341,9 +95370,18 @@ var ts; } break; case 147 /* Parameter */: - var functionDeclaration = parent.parent; - if (functionDeclaration.parameters.length === 1) { - changes.deleteNode(sourceFile, parent); + var oldFunction = parent.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, + /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + // Drop leading and trailing trivia of the new function because we're only going + // to replace the span (vs the full span) of the old function - the old leading + // and trailing trivia will remain. + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceRange(sourceFile, { pos: oldFunction.getStart(), end: oldFunction.end }, newFunction); } else { changes.deleteNodeInList(sourceFile, parent); @@ -93501,7 +95539,7 @@ var ts; return { span: ts.createTextSpanFromBounds(declaration.getStart(sourceFile), declaration.getEnd()), newText: newText }; } function typeString(type, checker) { - return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); + return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */); } function isTypeContainer(node) { // NOTE: Some locations are not handled yet: @@ -93733,7 +95771,6 @@ var ts; var symbolToken = ts.cast(ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false), ts.isIdentifier); return { host: context.host, - newLineCharacter: context.newLineCharacter, formatContext: context.formatContext, sourceFile: context.sourceFile, program: program, @@ -94001,7 +96038,7 @@ var ts; } function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { var roots = ts.getEffectiveTypeRoots(options, host); - return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); if (ts.startsWith(moduleFileName, typeRoot)) { return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); @@ -94381,10 +96418,11 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, newLineCharacter = context.newLineCharacter, span = context.span; + var sourceFile = context.sourceFile, program = context.program, span = context.span; if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } + var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)])], @@ -94406,7 +96444,7 @@ var ts; fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { if (err.start !== undefined) { - changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, context.newLineCharacter)); + changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options))); } }); }, }); @@ -94501,8 +96539,8 @@ var ts; outputMethod(signature, modifiers, name, createStubbedMethodBody()); break; } - for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { - var signature = signatures_9[_i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var signature = signatures_8[_i]; // Need to ensure nodes are fresh each time so they can have different positions. outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); } @@ -94523,7 +96561,7 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); if (!signatureDeclaration) { return undefined; } @@ -94574,8 +96612,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var _i = 0, signatures_10 = signatures; _i < signatures_10.length; _i++) { - var sig = signatures_10[_i]; + for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { + var sig = signatures_9[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -94822,7 +96860,7 @@ var ts; var typeIsAccessible = true; var writeText = function (text) { return str += text; }; return { - string: function () { return typeIsAccessible ? str : undefined; }, + getText: function () { return typeIsAccessible ? str : undefined; }, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -94831,6 +96869,15 @@ var ts; writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + write: writeText, + writeTextOfNode: writeText, + rawWrite: writeText, + writeLiteral: writeText, + getTextPos: function () { return 0; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return writeText(" "); }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -94847,8 +96894,8 @@ var ts; } function typeToString(type, enclosingDeclaration, checker) { var writer = getTypeAccessiblityWriter(checker); - checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); - return writer.string(); + checker.writeType(type, enclosingDeclaration, /*flags*/ undefined, writer); + return writer.getText(); } var InferFromReference; (function (InferFromReference) { @@ -95307,14 +97354,10 @@ var ts; (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { + var refactorName = "Annotate with type from JSDoc"; var actionName = "annotate"; - var annotateTypeFromJSDoc = { - name: "Annotate with type from JSDoc", - description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(annotateTypeFromJSDoc); + var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; @@ -95322,11 +97365,11 @@ var ts; var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: annotateTypeFromJSDoc.name, - description: annotateTypeFromJSDoc.description, + name: refactorName, + description: description, actions: [ { - description: annotateTypeFromJSDoc.description, + description: description, name: actionName } ] @@ -95536,15 +97579,11 @@ var ts; var refactor; (function (refactor) { var convertFunctionToES6Class; - (function (convertFunctionToES6Class_1) { + (function (convertFunctionToES6Class) { + var refactorName = "Convert to ES2015 class"; var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); + var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!ts.isInJavaScriptFile(context.file)) { return undefined; @@ -95559,11 +97598,11 @@ var ts; if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { return [ { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, + name: refactorName, + description: description, actions: [ { - description: convertFunctionToES6Class.description, + description: description, name: actionName } ] @@ -95779,13 +97818,8 @@ var ts; var refactor; (function (refactor) { var actionName = "Convert to ES6 module"; - var convertToEs6Module = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(convertToEs6Module); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition; if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { @@ -95794,11 +97828,11 @@ var ts; var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); return !isAtTriggerLocation(file, node) ? undefined : [ { - name: convertToEs6Module.name, - description: convertToEs6Module.description, + name: actionName, + description: description, actions: [ { - description: convertToEs6Module.description, + description: description, name: actionName, }, ], @@ -96268,14 +98302,9 @@ var ts; var refactor; (function (refactor) { var extractSymbol; - (function (extractSymbol_1) { - var extractSymbol = { - name: "Extract Symbol", - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction, - }; - refactor.registerRefactor(extractSymbol); + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); /** * Compute the associated code actions * Exported for tests. @@ -96333,21 +98362,21 @@ var ts; var infos = []; if (functionActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), actions: functionActions }); } if (constantActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), actions: constantActions }); } return infos.length ? infos : undefined; } - extractSymbol_1.getAvailableActions = getAvailableActions; + extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); @@ -96366,7 +98395,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol_1.getEditsForAction = getEditsForAction; + extractSymbol.getEditsForAction = getEditsForAction; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { @@ -96395,7 +98424,7 @@ var ts; Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -96682,7 +98711,7 @@ var ts; } } } - extractSymbol_1.getRangeToExtract = getRangeToExtract; + extractSymbol.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -96884,7 +98913,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -96912,7 +98941,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -96980,7 +99009,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -97091,7 +99120,7 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -97817,15 +99846,11 @@ var ts; var refactor; (function (refactor) { var installTypesForPackage; - (function (installTypesForPackage_1) { + (function (installTypesForPackage) { + var refactorName = "Install missing types package"; var actionName = "install"; - var installTypesForPackage = { - name: "Install missing types package", - description: "Install missing types package", - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(installTypesForPackage); + var description = "Install missing types package"; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { // Then it will be available via `fixCannotFindModule`. @@ -97834,8 +99859,8 @@ var ts; var action = getAction(context); return action && [ { - name: installTypesForPackage.name, - description: installTypesForPackage.description, + name: refactorName, + description: description, actions: [ { description: action.description, @@ -97890,13 +99915,8 @@ var ts; var installTypesForPackage; (function (installTypesForPackage) { var actionName = "Convert to default import"; - var useDefaultImport = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(useDefaultImport); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition, program = context.program; if (!program.getCompilerOptions().allowSyntheticDefaultImports) { @@ -97913,11 +99933,11 @@ var ts; } return [ { - name: useDefaultImport.name, - description: useDefaultImport.description, + name: actionName, + description: description, actions: [ { - description: useDefaultImport.description, + description: description, name: actionName, }, ], @@ -98528,9 +100548,9 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_7 = ts.getTextOfIdentifierOrLiteral(name); - if (result_7 !== undefined) { - return result_7; + var result_6 = ts.getTextOfIdentifierOrLiteral(name); + if (result_6 !== undefined) { + return result_6; } if (name.kind === 145 /* ComputedPropertyName */) { var expr = name.expression; @@ -98815,8 +100835,7 @@ var ts; sourceFile.scriptSnapshot = scriptSnapshot; } function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { - var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); return sourceFile; } @@ -98980,7 +100999,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -98990,7 +101009,7 @@ var ts; var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache.getEntryByPath(path); if (entry) { - return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } return host.readFile && host.readFile(fileName); }, @@ -99227,10 +101246,10 @@ var ts; function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); // Get occurrences only supports reporting occurrences for the file queried. So // filter down to that list. - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; }); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -99492,20 +101511,18 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } function getCombinedCodeFix(scope, fixId, formatOptions) { synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -99693,7 +101710,6 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, @@ -99829,20 +101845,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_8 = []; + 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_8.push(symbol); + result_7.push(symbol); } }); - return result_8; + return result_7; } if (symbol) { - result_8.push(symbol); - return result_8; + result_7.push(symbol); + return result_7; } } return undefined; @@ -101121,7 +103137,7 @@ var ts; var _this = this; return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { // for now treat files as JavaScript - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); return { referencedFiles: _this.convertFileReferences(result.referencedFiles), importedFiles: _this.convertFileReferences(result.importedFiles), @@ -101156,8 +103172,7 @@ var ts; CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { - var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseJsonText(fileName, text); + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); var normalizedFileName = ts.normalizeSlashes(fileName); var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 935c4311c0b..c7c9d5c3d0a 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -639,7 +639,7 @@ declare namespace ts { body?: Block | Expression; } type FunctionLikeDeclaration = FunctionDeclaration | MethodDeclaration | ConstructorDeclaration | GetAccessorDeclaration | SetAccessorDeclaration | FunctionExpression | ArrowFunction; - type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration; + type FunctionLike = FunctionLikeDeclaration | FunctionTypeNode | ConstructorTypeNode | IndexSignatureDeclaration | MethodSignature | ConstructSignatureDeclaration | CallSignatureDeclaration | JSDocFunctionType; interface FunctionDeclaration extends FunctionLikeDeclarationBase, DeclarationStatement { kind: SyntaxKind.FunctionDeclaration; name?: Identifier; @@ -877,7 +877,7 @@ declare namespace ts { type DestructuringAssignment = ObjectDestructuringAssignment | ArrayDestructuringAssignment; type BindingOrAssignmentElement = VariableDeclaration | ParameterDeclaration | BindingElement | PropertyAssignment | ShorthandPropertyAssignment | SpreadAssignment | OmittedExpression | SpreadElement | ArrayLiteralExpression | ObjectLiteralExpression | AssignmentExpression | Identifier | PropertyAccessExpression | ElementAccessExpression; type BindingOrAssignmentElementRestIndicator = DotDotDotToken | SpreadElement | SpreadAssignment; - type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Expression; + type BindingOrAssignmentElementTarget = BindingOrAssignmentPattern | Identifier | PropertyAccessExpression | ElementAccessExpression | OmittedExpression; type ObjectBindingOrAssignmentPattern = ObjectBindingPattern | ObjectLiteralExpression; type ArrayBindingOrAssignmentPattern = ArrayBindingPattern | ArrayLiteralExpression; type AssignmentPattern = ObjectLiteralExpression | ArrayLiteralExpression; @@ -1729,6 +1729,16 @@ declare namespace ts { signatureToSignatureDeclaration(signature: Signature, kind: SyntaxKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): SignatureDeclaration; /** Note that the resulting nodes cannot be checked. */ indexInfoToIndexSignatureDeclaration(indexInfo: IndexInfo, kind: IndexKind, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): IndexSignatureDeclaration; + /** Note that the resulting nodes cannot be checked. */ + symbolToEntityName(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): EntityName; + /** Note that the resulting nodes cannot be checked. */ + symbolToExpression(symbol: Symbol, meaning: SymbolFlags, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): Expression; + /** Note that the resulting nodes cannot be checked. */ + symbolToTypeParameterDeclarations(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): NodeArray | undefined; + /** Note that the resulting nodes cannot be checked. */ + symbolToParameterDeclaration(symbol: Symbol, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): ParameterDeclaration; + /** Note that the resulting nodes cannot be checked. */ + typeParameterToDeclaration(parameter: TypeParameter, enclosingDeclaration?: Node, flags?: NodeBuilderFlags): TypeParameterDeclaration; getSymbolsInScope(location: Node, meaning: SymbolFlags): Symbol[]; getSymbolAtLocation(node: Node): Symbol | undefined; getSymbolsOfParameterPropertyDeclaration(parameter: ParameterDeclaration, parameterName: string): Symbol[]; @@ -1748,7 +1758,8 @@ declare namespace ts { getTypeFromTypeNode(node: TypeNode): Type; signatureToString(signature: Signature, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): string; typeToString(type: Type, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; - symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): string; + symbolToString(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): string; + typePredicateToString(predicate: TypePredicate, enclosingDeclaration?: Node, flags?: TypeFormatFlags): string; /** * @deprecated Use the createX factory functions or XToY typechecker methods and `createPrinter` or the `xToString` methods instead * This will be removed in a future version. @@ -1788,33 +1799,79 @@ declare namespace ts { None = 0, NoTruncation = 1, WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, + WriteTypeArgumentsOfSignature = 32, + UseFullyQualifiedType = 64, + UseOnlyExternalAliasing = 128, + SuppressAnyReturnType = 256, + WriteTypeParametersInQualifiedName = 512, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowThisInObjectLiteral = 32768, + AllowQualifedNameInPlaceOfIdentifier = 65536, + AllowAnonymousIdentifier = 131072, + AllowEmptyUnionOrIntersection = 262144, + AllowEmptyTuple = 524288, + AllowUniqueESSymbolType = 1048576, + AllowEmptyIndexInfoType = 2097152, + IgnoreErrors = 3112960, + InObjectTypeLiteral = 4194304, + InTypeAlias = 8388608, + } + enum TypeFormatFlags { + None = 0, + NoTruncation = 1, + WriteArrayAsGenericType = 2, + WriteDefaultSymbolWithoutName = 4, + UseStructuralFallback = 8, WriteTypeArgumentsOfSignature = 32, UseFullyQualifiedType = 64, SuppressAnyReturnType = 256, - WriteTypeParametersInQualifiedName = 512, - AllowThisInObjectLiteral = 1024, - AllowQualifedNameInPlaceOfIdentifier = 2048, - AllowAnonymousIdentifier = 8192, - AllowEmptyUnionOrIntersection = 16384, - AllowEmptyTuple = 32768, - IgnoreErrors = 60416, - InObjectTypeLiteral = 1048576, + MultilineObjectLiterals = 1024, + WriteClassExpressionAsTypeLiteral = 2048, + UseTypeOfFunction = 4096, + OmitParameterModifiers = 8192, + UseAliasDefinedOutsideCurrentScope = 16384, + AllowUniqueESSymbolType = 1048576, + AddUndefined = 131072, + WriteArrowStyleSignature = 262144, + InArrayType = 524288, + InElementType = 2097152, + InFirstTypeArgument = 4194304, InTypeAlias = 8388608, + /** @deprecated */ WriteOwnNameForAnyLike = 0, + NodeBuilderFlagsMask = 9469295, } + enum SymbolFormatFlags { + None = 0, + WriteTypeParametersOrArguments = 1, + UseOnlyExternalAliasing = 2, + AllowAnyNodeKind = 4, + } + /** + * @deprecated + */ interface SymbolDisplayBuilder { - buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; - buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; - buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; - buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; - buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeDisplay(type: Type, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildSymbolDisplay(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, meaning?: SymbolFlags, flags?: SymbolFormatFlags): void; + /** @deprecated */ buildSignatureDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags, kind?: SignatureKind): void; + /** @deprecated */ buildIndexSignatureDisplay(info: IndexInfo, writer: SymbolWriter, kind: IndexKind, enclosingDeclaration?: Node, globalFlags?: TypeFormatFlags, symbolStack?: Symbol[]): void; + /** @deprecated */ buildParameterDisplay(parameter: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplay(tp: TypeParameter, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypePredicateDisplay(predicate: TypePredicate, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildTypeParameterDisplayFromSymbol(symbol: Symbol, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForParametersAndDelimiters(thisParameter: Symbol, parameters: Symbol[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildDisplayForTypeParametersAndDelimiters(typeParameters: TypeParameter[], writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; + /** @deprecated */ buildReturnTypeDisplay(signature: Signature, writer: SymbolWriter, enclosingDeclaration?: Node, flags?: TypeFormatFlags): void; } - interface SymbolWriter { + /** + * @deprecated Migrate to other methods of generating symbol names, ex symbolToEntityName + a printer or symbolToString + */ + interface SymbolWriter extends SymbolTracker { writeKeyword(text: string): void; writeOperator(text: string): void; writePunctuation(text: string): void; @@ -1827,34 +1884,6 @@ declare namespace ts { increaseIndent(): void; decreaseIndent(): void; clear(): void; - trackSymbol(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; - reportInaccessibleThisError(): void; - reportPrivateInBaseOfClassExpression(propertyName: string): void; - reportInaccessibleUniqueSymbolError(): void; - } - enum TypeFormatFlags { - None = 0, - WriteArrayAsGenericType = 1, - UseTypeOfFunction = 4, - NoTruncation = 8, - WriteArrowStyleSignature = 16, - WriteOwnNameForAnyLike = 32, - WriteTypeArgumentsOfSignature = 64, - InElementType = 128, - UseFullyQualifiedType = 256, - InFirstTypeArgument = 512, - InTypeAlias = 1024, - SuppressAnyReturnType = 4096, - AddUndefined = 8192, - WriteClassExpressionAsTypeLiteral = 16384, - InArrayType = 32768, - UseAliasDefinedOutsideCurrentScope = 65536, - AllowUniqueESSymbolType = 131072, - } - enum SymbolFormatFlags { - None = 0, - WriteTypeParametersOrArguments = 1, - UseOnlyExternalAliasing = 2, } enum TypePredicateKind { This = 0, @@ -2149,15 +2178,14 @@ declare namespace ts { declaration?: SignatureDeclaration; } enum InferencePriority { - Contravariant = 1, - NakedTypeVariable = 2, - MappedType = 4, - ReturnType = 8, - NeverType = 16, + NakedTypeVariable = 1, + MappedType = 2, + ReturnType = 4, } interface InferenceInfo { typeParameter: TypeParameter; candidates: Type[]; + contraCandidates: Type[]; inferredType: Type; priority: InferencePriority; topLevel: boolean; @@ -2478,6 +2506,7 @@ declare namespace ts { */ resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; getEnvironmentVariable?(name: string): string; + createHash?(data: string): string; } interface SourceMapRange extends TextRange { source?: SourceMapSource; @@ -2634,6 +2663,10 @@ declare namespace ts { * collisions. */ printNode(hint: EmitHint, node: Node, sourceFile: SourceFile): string; + /** + * Prints a list of nodes using the given format flags + */ + printList(format: ListFormat, list: NodeArray, sourceFile: SourceFile): string; /** * Prints a source file as-is, without any emit transformations. */ @@ -2689,6 +2722,13 @@ declare namespace ts { interface PrinterOptions { removeComments?: boolean; newLine?: NewLineKind; + omitTrailingSemicolon?: boolean; + } + interface SymbolTracker { + trackSymbol?(symbol: Symbol, enclosingDeclaration?: Node, meaning?: SymbolFlags): void; + reportInaccessibleThisError?(): void; + reportPrivateInBaseOfClassExpression?(propertyName: string): void; + reportInaccessibleUniqueSymbolError?(): void; } interface TextSpan { start: number; @@ -2701,6 +2741,71 @@ declare namespace ts { interface SyntaxList extends Node { _children: Node[]; } + enum ListFormat { + None = 0, + SingleLine = 0, + MultiLine = 1, + PreserveLines = 2, + LinesMask = 3, + NotDelimited = 0, + BarDelimited = 4, + AmpersandDelimited = 8, + CommaDelimited = 16, + DelimitersMask = 28, + AllowTrailingComma = 32, + Indented = 64, + SpaceBetweenBraces = 128, + SpaceBetweenSiblings = 256, + Braces = 512, + Parenthesis = 1024, + AngleBrackets = 2048, + SquareBrackets = 4096, + BracketsMask = 7680, + OptionalIfUndefined = 8192, + OptionalIfEmpty = 16384, + Optional = 24576, + PreferNewLine = 32768, + NoTrailingNewLine = 65536, + NoInterveningComments = 131072, + NoSpaceIfEmpty = 262144, + SingleElement = 524288, + Modifiers = 131328, + HeritageClauses = 256, + SingleLineTypeLiteralMembers = 448, + MultiLineTypeLiteralMembers = 65, + TupleTypeElements = 336, + UnionTypeConstituents = 260, + IntersectionTypeConstituents = 264, + ObjectBindingPatternElements = 262576, + ArrayBindingPatternElements = 262448, + ObjectLiteralExpressionProperties = 263122, + ArrayLiteralExpressionElements = 4466, + CommaListElements = 272, + CallExpressionArguments = 1296, + NewExpressionArguments = 9488, + TemplateExpressionSpans = 131072, + SingleLineBlockStatements = 384, + MultiLineBlockStatements = 65, + VariableDeclarationList = 272, + SingleLineFunctionBodyStatements = 384, + MultiLineFunctionBodyStatements = 1, + ClassHeritageClauses = 256, + ClassMembers = 65, + InterfaceMembers = 65, + EnumMembers = 81, + CaseBlockClauses = 65, + NamedImportsOrExportsElements = 432, + JsxElementOrFragmentChildren = 131072, + JsxElementAttributes = 131328, + CaseOrDefaultClauseStatements = 81985, + HeritageClauseTypes = 272, + SourceFileStatements = 65537, + Decorators = 24577, + TypeArguments = 26896, + TypeParameters = 26896, + Parameters = 1296, + IndexSignatureParameters = 4432, + } } declare namespace ts { const versionMajorMinor = "2.7"; @@ -2725,26 +2830,14 @@ declare namespace ts { callback: FileWatcherCallback; mtime?: Date; } - /** - * Partial interface of the System thats needed to support the caching of directory structure - */ - interface DirectoryStructureHost { + interface System { + args: string[]; newLine: string; useCaseSensitiveFileNames: boolean; write(s: string): void; readFile(path: string, encoding?: string): string | undefined; - writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; - fileExists(path: string): boolean; - directoryExists(path: string): boolean; - createDirectory(path: string): void; - getCurrentDirectory(): string; - getDirectories(path: string): string[]; - readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; - exit(exitCode?: number): void; - } - interface System extends DirectoryStructureHost { - args: string[]; getFileSize?(path: string): number; + writeFile(path: string, data: string, writeByteOrderMark?: boolean): void; /** * @pollingInterval - this parameter is used in polling-based watchers and ignored in watchers that * use native OS file watching @@ -2752,7 +2845,13 @@ declare namespace ts { watchFile?(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; watchDirectory?(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; resolvePath(path: string): string; + fileExists(path: string): boolean; + directoryExists(path: string): boolean; + createDirectory(path: string): void; getExecutingFilePath(): string; + getCurrentDirectory(): string; + getDirectories(path: string): string[]; + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; getModifiedTime?(path: string): Date; /** * This should be cryptographically secure. @@ -2760,6 +2859,7 @@ declare namespace ts { */ createHash?(data: string): string; getMemoryUsage?(): number; + exit(exitCode?: number): void; realpath?(path: string): string; setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; clearTimeout?(timeoutId: any): void; @@ -2812,8 +2912,10 @@ declare namespace ts { function isWhiteSpaceSingleLine(ch: number): boolean; function isLineBreak(ch: number): boolean; function couldStartTrivia(text: string, pos: number): boolean; - function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; - function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state?: T): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean) => U): U | undefined; + function forEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T) => U, state: T): U | undefined; function reduceEachLeadingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function reduceEachTrailingCommentRange(text: string, pos: number, cb: (pos: number, end: number, kind: CommentKind, hasTrailingNewLine: boolean, state: T, memo: U) => U, state: T, initial: U): U; function getLeadingCommentRanges(text: string, pos: number): CommentRange[] | undefined; @@ -3243,7 +3345,7 @@ declare namespace ts { function createLiteral(value: string | number | boolean): PrimaryExpression; function createNumericLiteral(value: string): NumericLiteral; function createIdentifier(text: string): Identifier; - function updateIdentifier(node: Identifier, typeArguments: NodeArray | undefined): Identifier; + function updateIdentifier(node: Identifier): Identifier; /** Create a unique temporary variable. */ function createTempVariable(recordTempVariable: ((node: Identifier) => void) | undefined): Identifier; /** Create a unique temporary variable for use in a loop. */ @@ -3711,17 +3813,6 @@ declare namespace ts { declare namespace ts { function createPrinter(printerOptions?: PrinterOptions, handlers?: PrintHandlers): Printer; } -declare namespace ts { - interface EmitOutput { - outputFiles: OutputFile[]; - emitSkipped: boolean; - } - interface OutputFile { - name: string; - writeByteOrderMark: boolean; - text: string; - } -} declare namespace ts { function findConfigFile(searchPath: string, fileExists: (fileName: string) => boolean, configName?: string): string | undefined; function resolveTripleslashReference(moduleName: string, containingFile: string): string; @@ -3751,6 +3842,258 @@ declare namespace ts { */ function createProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: Program): Program; } +declare namespace ts { + interface EmitOutput { + outputFiles: OutputFile[]; + emitSkipped: boolean; + } + interface OutputFile { + name: string; + writeByteOrderMark: boolean; + text: string; + } +} +declare namespace ts { + type AffectedFileResult = { + result: T; + affected: SourceFile | Program; + } | undefined; + interface BuilderProgramHost { + /** + * return true if file names are treated with case sensitivity + */ + useCaseSensitiveFileNames(): boolean; + /** + * If provided this would be used this hash instead of actual file shape text for detecting changes + */ + createHash?: (data: string) => string; + /** + * When emit or emitNextAffectedFile are called without writeFile, + * this callback if present would be used to write files + */ + writeFile?: WriteFileCallback; + } + /** + * Builder to manage the program state changes + */ + interface BuilderProgram { + /** + * Returns current program + */ + getProgram(): Program; + /** + * Get compiler options of the program + */ + getCompilerOptions(): CompilerOptions; + /** + * Get the source file in the program with file name + */ + getSourceFile(fileName: string): SourceFile | undefined; + /** + * Get a list of files in the program + */ + getSourceFiles(): ReadonlyArray; + /** + * Get the diagnostics for compiler options + */ + getOptionsDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the diagnostics that dont belong to any file + */ + getGlobalDiagnostics(cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get the syntax diagnostics, for all source files if source file is not supplied + */ + getSyntacticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Get all the dependencies of the file + */ + getAllDependencies(sourceFile: SourceFile): ReadonlyArray; + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + getSemanticDiagnostics(sourceFile?: SourceFile, cancellationToken?: CancellationToken): ReadonlyArray; + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emit(targetSourceFile?: SourceFile, writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): EmitResult; + /** + * Get the current directory of the program + */ + getCurrentDirectory(): string; + } + /** + * The builder that caches the semantic diagnostics for the program and handles the changed files and affected files + */ + interface SemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Gets the semantic diagnostics from the program for the next affected file and caches it + * Returns undefined if the iteration is complete + */ + getSemanticDiagnosticsOfNextAffectedFile(cancellationToken?: CancellationToken, ignoreSourceFile?: (sourceFile: SourceFile) => boolean): AffectedFileResult>; + } + /** + * The builder that can handle the changes in program and iterate through changed file to emit the files + * The semantic diagnostics are cached per file and managed by clearing for the changed/affected files + */ + interface EmitAndSemanticDiagnosticsBuilderProgram extends BuilderProgram { + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + emitNextAffectedFile(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken, emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers): AffectedFileResult; + } + /** + * Create the builder to manage semantic diagnostics and cache them + */ + function createSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + function createSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: SemanticDiagnosticsBuilderProgram): SemanticDiagnosticsBuilderProgram; + /** + * Create the builder that can handle the changes in program and iterate through changed files + * to emit the those files and manage semantic diagnostics cache as well + */ + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgram: Program, host: BuilderProgramHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: EmitAndSemanticDiagnosticsBuilderProgram): EmitAndSemanticDiagnosticsBuilderProgram; + /** + * Creates a builder thats just abstraction over program and can be used with watch + */ + function createAbstractBuilder(newProgram: Program, host: BuilderProgramHost, oldProgram?: BuilderProgram): BuilderProgram; + function createAbstractBuilder(rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: BuilderProgram): BuilderProgram; +} +declare namespace ts { + type DiagnosticReporter = (diagnostic: Diagnostic) => void; + type WatchStatusReporter = (diagnostic: Diagnostic, newLine: string) => void; + type CreateProgram = (rootNames: ReadonlyArray, options: CompilerOptions, host?: CompilerHost, oldProgram?: T) => T; + interface WatchCompilerHost { + /** + * Used to create the program when need for program creation or recreation detected + */ + createProgram: CreateProgram; + /** If provided, callback to invoke after every new program creation */ + afterProgramCreate?(program: T): void; + /** If provided, called with Diagnostic message that informs about change in watch status */ + onWatchStatusChange?(diagnostic: Diagnostic, newLine: string): void; + useCaseSensitiveFileNames(): boolean; + getNewLine(): string; + getCurrentDirectory(): string; + getDefaultLibFileName(options: CompilerOptions): string; + getDefaultLibLocation?(): string; + createHash?(data: string): string; + /** + * Use to check file presence for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + fileExists(path: string): boolean; + /** + * Use to read file text for source files and + * if resolveModuleNames is not provided (complier is in charge of module resolution) then module files as well + */ + readFile(path: string, encoding?: string): string | undefined; + /** If provided, used for module resolution as well as to handle directory structure */ + directoryExists?(path: string): boolean; + /** If provided, used in resolutions as well as handling directory structure */ + getDirectories?(path: string): string[]; + /** If provided, used to cache and handle directory structure modifications */ + readDirectory?(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + /** Symbol links resolution */ + realpath?(path: string): string; + /** If provided would be used to write log about compilation */ + trace?(s: string): void; + /** If provided is used to get the environment variable */ + getEnvironmentVariable?(name: string): string; + /** If provided, used to resolve the module names, otherwise typescript's default module resolution */ + resolveModuleNames?(moduleNames: string[], containingFile: string, reusedNames?: string[]): ResolvedModule[]; + /** If provided, used to resolve type reference directives, otherwise typescript's default resolution */ + resolveTypeReferenceDirectives?(typeReferenceDirectiveNames: string[], containingFile: string): (ResolvedTypeReferenceDirective | undefined)[]; + /** Used to watch changes in source files, missing files needed to update the program or config file */ + watchFile(path: string, callback: FileWatcherCallback, pollingInterval?: number): FileWatcher; + /** Used to watch resolved module's failed lookup locations, config file specs, type roots where auto type reference directives are added */ + watchDirectory(path: string, callback: DirectoryWatcherCallback, recursive?: boolean): FileWatcher; + /** If provided, will be used to set delayed compilation, so that multiple changes in short span are compiled together */ + setTimeout?(callback: (...args: any[]) => void, ms: number, ...args: any[]): any; + /** If provided, will be used to reset existing delayed compilation */ + clearTimeout?(timeoutId: any): void; + } + /** + * Host to create watch with root files and options + */ + interface WatchCompilerHostOfFilesAndCompilerOptions extends WatchCompilerHost { + /** root files to use to generate program */ + rootFiles: string[]; + /** Compiler options */ + options: CompilerOptions; + } + /** + * Reports config file diagnostics + */ + interface ConfigFileDiagnosticsReporter { + /** + * Reports the diagnostics in reading/writing or parsing of the config file + */ + onConfigFileDiagnostic: DiagnosticReporter; + /** + * Reports unrecoverable error when parsing config file + */ + onUnRecoverableConfigFileDiagnostic: DiagnosticReporter; + } + /** + * Host to create watch with config file + */ + interface WatchCompilerHostOfConfigFile extends WatchCompilerHost, ConfigFileDiagnosticsReporter { + /** Name of the config file to compile */ + configFileName: string; + /** Options to extend */ + optionsToExtend?: CompilerOptions; + /** + * Used to generate source file names from the config file and its include, exclude, files rules + * and also to cache the directory stucture + */ + readDirectory(path: string, extensions?: ReadonlyArray, exclude?: ReadonlyArray, include?: ReadonlyArray, depth?: number): string[]; + } + interface Watch { + /** Synchronize with host and get updated program */ + getProgram(): T; + } + /** + * Creates the watch what generates program using the config file + */ + interface WatchOfConfigFile extends Watch { + } + /** + * Creates the watch that generates program using the root files and compiler options + */ + interface WatchOfFilesAndCompilerOptions extends Watch { + /** Updates the root files in the program, only if this is not config file compilation */ + updateRootFileNames(fileNames: string[]): void; + } + /** + * Create the watch compiler host for either configFile or fileNames and its options + */ + function createWatchCompilerHost(rootFiles: string[], options: CompilerOptions, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfFilesAndCompilerOptions; + function createWatchCompilerHost(configFileName: string, optionsToExtend: CompilerOptions | undefined, system: System, createProgram?: CreateProgram, reportDiagnostic?: DiagnosticReporter, reportWatchStatus?: WatchStatusReporter): WatchCompilerHostOfConfigFile; + /** + * Creates the watch from the host for root files and compiler options + */ + function createWatchProgram(host: WatchCompilerHostOfFilesAndCompilerOptions): WatchOfFilesAndCompilerOptions; + /** + * Creates the watch from the host for config file + */ + function createWatchProgram(host: WatchCompilerHostOfConfigFile): WatchOfConfigFile; +} declare namespace ts { function parseCommandLine(commandLine: ReadonlyArray, readFile?: (path: string) => string | undefined): ParsedCommandLine; /** @@ -3985,7 +4328,8 @@ 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; - getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: ReadonlyArray, formatOptions: FormatCodeSettings): ReadonlyArray; + getCombinedCodeFix(scope: CombinedCodeFixScope, fixId: {}, formatOptions: FormatCodeSettings): CombinedCodeActions; applyCodeActionCommand(action: CodeActionCommand): Promise; applyCodeActionCommand(action: CodeActionCommand[]): Promise; applyCodeActionCommand(action: CodeActionCommand | CodeActionCommand[]): Promise; @@ -4001,6 +4345,10 @@ declare namespace ts { getProgram(): Program; dispose(): void; } + interface CombinedCodeFixScope { + type: "file"; + fileName: string; + } interface GetCompletionsAtPositionOptions { includeExternalModuleExports: boolean; includeInsertTextCompletions: boolean; @@ -4078,6 +4426,17 @@ declare namespace ts { */ commands?: CodeActionCommand[]; } + interface CodeFixAction extends CodeAction { + /** + * 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?: {}; + } + interface CombinedCodeActions { + changes: ReadonlyArray; + commands: ReadonlyArray | undefined; + } type CodeActionCommand = InstallPackageAction; interface InstallPackageAction { } @@ -4661,9 +5020,6 @@ declare namespace ts { declare namespace ts { /** The version of the language service API */ const servicesVersion = "0.7"; - interface DisplayPartsSymbolWriter extends SymbolWriter { - displayParts(): SymbolDisplayPart[]; - } function toEditorSettings(options: EditorOptions | EditorSettings): EditorSettings; function displayPartsToString(displayParts: SymbolDisplayPart[]): string; function getDefaultCompilerOptions(): CompilerOptions; diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index c858823e640..4c73d04ba23 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -489,14 +489,19 @@ var ts; RelationComparisonResult[RelationComparisonResult["FailedAndReported"] = 3] = "FailedAndReported"; })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {})); /*@internal*/ - var GeneratedIdentifierKind; - (function (GeneratedIdentifierKind) { - GeneratedIdentifierKind[GeneratedIdentifierKind["None"] = 0] = "None"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Auto"] = 1] = "Auto"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Loop"] = 2] = "Loop"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Unique"] = 3] = "Unique"; - GeneratedIdentifierKind[GeneratedIdentifierKind["Node"] = 4] = "Node"; - })(GeneratedIdentifierKind = ts.GeneratedIdentifierKind || (ts.GeneratedIdentifierKind = {})); + var GeneratedIdentifierFlags; + (function (GeneratedIdentifierFlags) { + // Kinds + 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"; + // Flags + GeneratedIdentifierFlags[GeneratedIdentifierFlags["SkipNameGenerationScope"] = 8] = "SkipNameGenerationScope"; + GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 16] = "ReservedInNestedScopes"; + })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {})); /* @internal */ var TokenFlags; (function (TokenFlags) { @@ -570,47 +575,70 @@ var ts; // Options NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + NodeBuilderFlags[NodeBuilderFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // empty space 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"; // Error handling - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; + 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"; // State - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; + NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral"; NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); + // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment var TypeFormatFlags; (function (TypeFormatFlags) { TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None"; - TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 1] = "WriteArrayAsGenericType"; - TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4] = "UseTypeOfFunction"; - TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 8] = "NoTruncation"; - TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 16] = "WriteArrowStyleSignature"; - TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 32] = "WriteOwnNameForAnyLike"; - TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 64] = "WriteTypeArgumentsOfSignature"; - TypeFormatFlags[TypeFormatFlags["InElementType"] = 128] = "InElementType"; - TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 256] = "UseFullyQualifiedType"; - TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 512] = "InFirstTypeArgument"; - TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 1024] = "InTypeAlias"; - TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 4096] = "SuppressAnyReturnType"; - TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 8192] = "AddUndefined"; - TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 16384] = "WriteClassExpressionAsTypeLiteral"; - TypeFormatFlags[TypeFormatFlags["InArrayType"] = 32768] = "InArrayType"; - TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 65536] = "UseAliasDefinedOutsideCurrentScope"; + TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation"; + TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; + TypeFormatFlags[TypeFormatFlags["WriteDefaultSymbolWithoutName"] = 4] = "WriteDefaultSymbolWithoutName"; + TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback"; + // hole because there's a hole in node builder flags + TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; + TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; + // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead + TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; + // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead + 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"; // even though `T` can't be accessed in the current scope. - TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 131072] = "AllowUniqueESSymbolType"; + // Error Handling + TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType"; + // TypeFormatFlags exclusive + TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined"; + TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature"; + // State + TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType"; + TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType"; + TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument"; + TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; + /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike"; + TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 9469295] = "NodeBuilderFlagsMask"; })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {})); var SymbolFormatFlags; (function (SymbolFormatFlags) { SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None"; // Write symbols's type argument if it is instantiated symbol - // eg. class C { p: T } <-- Show p as C.p here + // eg. class C { p: T } <-- Show p as C.p here // var a: C; // var p = a.p; <--- Here p is property of C so show it as C.p instead of just C.p SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments"; @@ -618,6 +646,8 @@ var ts; // eg. module m { export class c { } } import x = m.c; // When this flag is specified m.c will be used to refer to the class instead of alias symbol x SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing"; + // Build symbol name using any nodes needed, instead of just components of an entity name + SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind"; })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {})); /* @internal */ var SymbolAccessibility; @@ -904,11 +934,9 @@ var ts; })(IndexKind = ts.IndexKind || (ts.IndexKind = {})); var InferencePriority; (function (InferencePriority) { - InferencePriority[InferencePriority["Contravariant"] = 1] = "Contravariant"; - InferencePriority[InferencePriority["NakedTypeVariable"] = 2] = "NakedTypeVariable"; - InferencePriority[InferencePriority["MappedType"] = 4] = "MappedType"; - InferencePriority[InferencePriority["ReturnType"] = 8] = "ReturnType"; - InferencePriority[InferencePriority["NeverType"] = 16] = "NeverType"; + InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable"; + InferencePriority[InferencePriority["MappedType"] = 2] = "MappedType"; + InferencePriority[InferencePriority["ReturnType"] = 4] = "ReturnType"; })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {})); var InferenceFlags; (function (InferenceFlags) { @@ -1191,6 +1219,8 @@ var ts; 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"; // Please leave this as 1 << 29. // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system. // It is a good reminder of how much room we have left @@ -1208,20 +1238,22 @@ var ts; // Scope Exclusions // - Bitmasks that exclude flags from propagating out of a specific context // into the subtree flags of their container. - TransformFlags[TransformFlags["NodeExcludes"] = 536872257] = "NodeExcludes"; - TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 601249089] = "ArrowFunctionExcludes"; - TransformFlags[TransformFlags["FunctionExcludes"] = 601281857] = "FunctionExcludes"; - TransformFlags[TransformFlags["ConstructorExcludes"] = 601015617] = "ConstructorExcludes"; - TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 601015617] = "MethodOrAccessorExcludes"; - TransformFlags[TransformFlags["ClassExcludes"] = 539358529] = "ClassExcludes"; - TransformFlags[TransformFlags["ModuleExcludes"] = 574674241] = "ModuleExcludes"; + 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"] = 540087617] = "ObjectLiteralExcludes"; - TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 537396545] = "ArrayLiteralOrCallOrNewExcludes"; - TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 546309441] = "VariableDeclarationListExcludes"; - TransformFlags[TransformFlags["ParameterExcludes"] = 536872257] = "ParameterExcludes"; - TransformFlags[TransformFlags["CatchClauseExcludes"] = 537920833] = "CatchClauseExcludes"; - TransformFlags[TransformFlags["BindingPatternExcludes"] = 537396545] = "BindingPatternExcludes"; + 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"; // Masks // - Additional bitmasks TransformFlags[TransformFlags["TypeScriptClassSyntaxMask"] = 274432] = "TypeScriptClassSyntaxMask"; @@ -1305,6 +1337,78 @@ var ts; EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter"; EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified"; })(EmitHint = ts.EmitHint || (ts.EmitHint = {})); + var ListFormat; + (function (ListFormat) { + ListFormat[ListFormat["None"] = 0] = "None"; + // Line separators + ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; + ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; + ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; + ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; + // Delimiters + 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"; + // Whitespace + ListFormat[ListFormat["Indented"] = 64] = "Indented"; + ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; + ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; + // Brackets/Braces + 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"; + // Other + 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"; + // Precomputed Formats + ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; + ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; + ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; + ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; + ListFormat[ListFormat["TupleTypeElements"] = 336] = "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"] = 256] = "ClassHeritageClauses"; + ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; + ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; + ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; + ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; + ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "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 = {})); })(ts || (ts = {})); /*@internal*/ var ts; @@ -1407,7 +1511,7 @@ var ts; // If changing the text in this section, be sure to test `configureNightly` too. ts.versionMajorMinor = "2.7"; /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -1420,6 +1524,7 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { + ts.emptyArray = []; /** Create a MapLike with good performance. */ function createDictionaryObject() { var map = Object.create(/*prototype*/ null); // tslint:disable-line:no-null-keyword @@ -1563,6 +1668,9 @@ var ts; ts.forEach = forEach; /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */ function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -2220,7 +2328,7 @@ var ts; var result = 0; for (var _i = 0, array_5 = array; _i < array_5.length; _i++) { var v = array_5[_i]; - // Note: we need the following type assertion because of GH #17069 + // TODO: Remove the following type assertion once the fix for #17069 is merged result += v[prop]; } return result; @@ -2727,6 +2835,9 @@ var ts; /** Returns its argument. */ function identity(x) { return x; } ts.identity = identity; + /** Returns lower case string */ + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; /** Throws an error because a function is not implemented. */ function notImplemented() { throw new Error("Not implemented"); @@ -3131,7 +3242,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58 /* colon */) { - if (path.charCodeAt(2) === 47 /* slash */) + if (path.charCodeAt(2) === 47 /* slash */ || path.charCodeAt(2) === 92 /* backslash */) return 3; } // Per RFC 1738 'file' URI schema has the shape file:/// @@ -3908,10 +4019,10 @@ var ts; } function Signature() { } // tslint:disable-line no-empty function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0 /* None */; this.modifierFlagsCache = 0 /* None */; this.transformFlags = 0 /* None */; @@ -4051,9 +4162,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; /** @@ -4172,182 +4281,16 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } // tslint:disable-line no-empty ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - /** - * If the readDirectory result was already cached, it returns that - * Otherwise gets result from host and caches it. - * The host request is done under try catch block to avoid caching incorrect result - */ - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - // If there is exception to read directories, dont cache the result and direct the calls to host - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - // Just clear the cache for now - // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated - clearCache(); - } - else { - // This was earlier a file (hence not in cached directory contents) - // or we never cached the directory containing it - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - // Folder added or removed, clear the cache instead of updating the folder and its structure - clearCache(); - } - else { - // No need to update the directory structure, just files - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } - } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -4626,7 +4569,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -4746,7 +4689,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -5342,6 +5290,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -5601,7 +5550,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -5710,6 +5659,7 @@ var ts; Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), 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."), @@ -5819,7 +5769,6 @@ var ts; Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -7713,7 +7662,6 @@ var ts; /* @internal */ var ts; (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -7736,15 +7684,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, // Completely ignore indentation for string writers. And map newlines to // a single space. writeLine: function () { return str += " "; }, @@ -7758,10 +7715,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -7802,6 +7759,12 @@ var ts; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -9206,41 +9169,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 /* EqualsToken */ && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 /* ModuleDeclaration */ && node.body && node.body.kind === 234 /* ModuleDeclaration */ && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -9381,6 +9333,33 @@ var ts; return getAssignmentTargetKind(node) !== 0 /* None */; } ts.isAssignmentTarget = isAssignmentTarget; + /** + * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to + * the same `var` declaration scope as the node's parent. + */ + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208 /* Block */: + case 209 /* VariableStatement */: + case 221 /* WithStatement */: + case 212 /* IfStatement */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 223 /* LabeledStatement */: + case 215 /* ForStatement */: + case 216 /* ForInStatement */: + case 217 /* ForOfStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 225 /* TryStatement */: + case 264 /* CatchClause */: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -10166,7 +10145,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -10806,14 +10797,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0 /* CarriageReturnLineFeed */: return carriageReturnLineFeed; case 1 /* LineFeed */: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; /** @@ -12038,7 +12029,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192 /* AwaitExpression */; + return node.kind === 190 /* TypeOfExpression */; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -12511,7 +12502,7 @@ var ts; /* @internal */ function isGeneratedIdentifier(node) { // Using `>` here catches both `GeneratedIdentifierKind.None` and `undefined`. - return ts.isIdentifier(node) && node.autoGenerateKind > 0 /* None */; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */; } ts.isGeneratedIdentifier = isGeneratedIdentifier; // Keywords @@ -13351,8 +13342,8 @@ var ts; case 177 /* BindingElement */: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 161 /* FunctionType */: @@ -18799,7 +18790,6 @@ var ts; scanner.scanRange(start + 3, length - 5, function () { // Initially we can parse out a tag. We also have seen a starting asterisk. // This is so that /** * @type */ doesn't parse. - var advanceToken = true; var state = 1 /* SawAsterisk */; var margin = undefined; // + 4 for leading '/** ' @@ -18830,7 +18820,6 @@ var ts; // 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 */` state = 0 /* BeginningOfLine */; - advanceToken = false; margin = undefined; indent++; } @@ -18882,13 +18871,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - t = nextJSDocToken(); - } - else { - advanceToken = true; - t = currentToken; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -18973,7 +18956,8 @@ var ts; // a badly malformed tag should not be added to the list of tags return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -18997,6 +18981,8 @@ var ts; indent = 0; break; case 57 /* AtToken */: + scanner.setTextPos(scanner.getTextPos() - 1); + // falls through case 1 /* EndOfFileToken */: // Done break loop; @@ -19031,7 +19017,7 @@ var ts; } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281 /* JSDocTag */, atToken.pos); @@ -19039,8 +19025,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -19302,34 +19287,44 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 /* Property */ && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 /* Property */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0 /* Property */; + break; case "arg": case "argument": case "param": - return target === 1 /* Parameter */ && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1 /* Parameter */; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287 /* JSDocTemplateTag */; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } // Type parameter list looks like '@template T,U,V' var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146 /* TypeParameter */); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146 /* TypeParameter */, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -19348,6 +19343,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17 /* OpenBraceToken */); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18 /* CloseBraceToken */); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -22339,6 +22342,8 @@ var ts; return computeImportEquals(node, subtreeFlags); case 180 /* PropertyAccessExpression */: return computePropertyAccess(node, subtreeFlags); + case 181 /* ElementAccessExpression */: + return computeElementAccess(node, subtreeFlags); default: return computeOther(node, kind, subtreeFlags); } @@ -22347,15 +22352,19 @@ var ts; function computeCallExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; var expression = node.expression; - var expressionKind = expression.kind; if (node.typeArguments) { transformFlags |= 3 /* AssertTypeScript */; } if (subtreeFlags & 524288 /* ContainsSpread */ - || isSuperOrSuperProperty(expression, expressionKind)) { + || (expression.transformFlags & (134217728 /* Super */ | 268435456 /* ContainsSuper */))) { // If the this node contains a SpreadExpression, or is a super call, then it is an ES6 // node. transformFlags |= 192 /* AssertES2015 */; + // super property or element accesses could be inside lambdas, etc, and need a captured `this`, + // while super keyword for super calls (indicated by TransformFlags.Super) does not (since it can only be top-level in a constructor) + if (expression.transformFlags & 268435456 /* ContainsSuper */) { + transformFlags |= 16384 /* ContainsLexicalThis */; + } } if (expression.kind === 91 /* ImportKeyword */) { transformFlags |= 67108864 /* ContainsDynamicImport */; @@ -22366,19 +22375,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; - } - function isSuperOrSuperProperty(node, kind) { - switch (kind) { - case 97 /* SuperKeyword */: - return true; - case 180 /* PropertyAccessExpression */: - case 181 /* ElementAccessExpression */: - var expression = node.expression; - var expressionKind = expression.kind; - return expressionKind === 97 /* SuperKeyword */; - } - return false; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeNewExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22391,7 +22388,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return transformFlags & ~940049729 /* ArrayLiteralOrCallOrNewExcludes */; } function computeBinaryExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22412,7 +22409,7 @@ var ts; transformFlags |= 32 /* AssertES2016 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeParameter(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22441,7 +22438,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 131072 /* ContainsDefaultValueAssignments */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* ParameterExcludes */; + return transformFlags & ~939525441 /* ParameterExcludes */; } function computeParenthesizedExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22461,7 +22458,7 @@ var ts; transformFlags |= 1024 /* DestructuringAssignment */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~536872257 /* OuterExpressionExcludes */; } function computeClassDeclaration(node, subtreeFlags) { var transformFlags; @@ -22487,7 +22484,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeClassExpression(node, subtreeFlags) { // A ClassExpression is ES6 syntax. @@ -22504,7 +22501,7 @@ var ts; transformFlags |= 16384 /* ContainsLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~539358529 /* ClassExcludes */; + return transformFlags & ~942011713 /* ClassExcludes */; } function computeHeritageClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22522,7 +22519,7 @@ var ts; break; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeCatchClause(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22533,7 +22530,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~537920833 /* CatchClauseExcludes */; + return transformFlags & ~940574017 /* CatchClauseExcludes */; } function computeExpressionWithTypeArguments(node, subtreeFlags) { // An ExpressionWithTypeArguments is ES6 syntax, as it is used in the @@ -22545,7 +22542,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeConstructor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22559,7 +22556,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* ConstructorExcludes */; + return transformFlags & ~1003668801 /* ConstructorExcludes */; } function computeMethod(node, subtreeFlags) { // A MethodDeclaration is ES6 syntax. @@ -22586,7 +22583,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computeAccessor(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22604,7 +22601,7 @@ var ts; transformFlags |= 8 /* AssertESNext */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601015617 /* MethodOrAccessorExcludes */; + return transformFlags & ~1003668801 /* MethodOrAccessorExcludes */; } function computePropertyDeclaration(node, subtreeFlags) { // A PropertyDeclaration is TypeScript syntax. @@ -22615,7 +22612,7 @@ var ts; transformFlags |= 8192 /* ContainsPropertyInitializer */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeFunctionDeclaration(node, subtreeFlags) { var transformFlags; @@ -22659,7 +22656,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeFunctionExpression(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22691,7 +22688,7 @@ var ts; transformFlags |= 768 /* AssertGenerator */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601281857 /* FunctionExcludes */; + return transformFlags & ~1003935041 /* FunctionExcludes */; } function computeArrowFunction(node, subtreeFlags) { // An ArrowFunction is ES6 syntax, and excludes markers that should not escape the scope of an ArrowFunction. @@ -22716,19 +22713,31 @@ var ts; transformFlags |= 32768 /* ContainsCapturedLexicalThis */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~601249089 /* ArrowFunctionExcludes */; + return transformFlags & ~1003902273 /* ArrowFunctionExcludes */; } function computePropertyAccess(node, subtreeFlags) { var transformFlags = subtreeFlags; - var expression = node.expression; - var expressionKind = expression.kind; // If a PropertyAccessExpression starts with a super keyword, then it is // ES6 syntax, and requires a lexical `this` binding. - if (expressionKind === 97 /* SuperKeyword */) { - transformFlags |= 16384 /* ContainsLexicalThis */; + if (transformFlags & 134217728 /* Super */) { + transformFlags ^= 134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; + } + function computeElementAccess(node, subtreeFlags) { + var transformFlags = subtreeFlags; + var expression = node.expression; + var expressionFlags = expression.transformFlags; // We do not want to aggregate flags from the argument expression for super/this capturing + // If an ElementAccessExpression starts with a super keyword, then it is + // ES6 syntax, and requires a lexical `this` binding. + if (expressionFlags & 134217728 /* Super */) { + transformFlags &= ~134217728 /* Super */; + transformFlags |= 268435456 /* ContainsSuper */; + } + node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; + return transformFlags & ~671089985 /* PropertyAccessExcludes */; } function computeVariableDeclaration(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22742,7 +22751,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeVariableStatement(node, subtreeFlags) { var transformFlags; @@ -22758,7 +22767,7 @@ var ts; } } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeLabeledStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22768,7 +22777,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeImportEquals(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22777,7 +22786,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeExpressionStatement(node, subtreeFlags) { var transformFlags = subtreeFlags; @@ -22788,7 +22797,7 @@ var ts; transformFlags |= 192 /* AssertES2015 */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~536872257 /* NodeExcludes */; + return transformFlags & ~939525441 /* NodeExcludes */; } function computeModuleDeclaration(node, subtreeFlags) { var transformFlags = 3 /* AssertTypeScript */; @@ -22797,7 +22806,7 @@ var ts; transformFlags |= subtreeFlags; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~574674241 /* ModuleExcludes */; + return transformFlags & ~977327425 /* ModuleExcludes */; } function computeVariableDeclarationList(node, subtreeFlags) { var transformFlags = subtreeFlags | 33554432 /* ContainsHoistedDeclarationOrCompletion */; @@ -22809,18 +22818,25 @@ var ts; transformFlags |= 192 /* AssertES2015 */ | 4194304 /* ContainsBlockScopedBinding */; } node.transformFlags = transformFlags | 536870912 /* HasComputedFlags */; - return transformFlags & ~546309441 /* VariableDeclarationListExcludes */; + return transformFlags & ~948962625 /* VariableDeclarationListExcludes */; } function computeOther(node, kind, subtreeFlags) { // Mark transformations needed for each node var transformFlags = subtreeFlags; - var excludeFlags = 536872257 /* NodeExcludes */; + var excludeFlags = 939525441 /* NodeExcludes */; switch (kind) { case 120 /* AsyncKeyword */: case 192 /* AwaitExpression */: // async/await is ES2017 syntax, but may be ESNext syntax (for async generators) transformFlags |= 8 /* AssertESNext */ | 16 /* AssertES2017 */; break; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + // These nodes are TypeScript syntax. + transformFlags |= 3 /* AssertTypeScript */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; + break; case 114 /* PublicKeyword */: case 112 /* PrivateKeyword */: case 113 /* ProtectedKeyword */: @@ -22829,8 +22845,6 @@ var ts; case 76 /* ConstKeyword */: case 233 /* EnumDeclaration */: case 268 /* EnumMember */: - case 185 /* TypeAssertionExpression */: - case 203 /* AsExpression */: case 204 /* NonNullExpression */: case 131 /* ReadonlyKeyword */: // These nodes are TypeScript syntax. @@ -22947,7 +22961,8 @@ var ts; break; case 97 /* SuperKeyword */: // This node is ES6 syntax. - transformFlags |= 192 /* AssertES2015 */; + transformFlags |= 192 /* AssertES2015 */ | 134217728 /* Super */; + excludeFlags = 536872257 /* OuterExpressionExcludes */; // must be set to persist `Super` break; case 99 /* ThisKeyword */: // Mark this node and its ancestors as containing a lexical `this` keyword. @@ -22958,11 +22973,11 @@ var ts; if (subtreeFlags & 524288 /* ContainsRest */) { transformFlags |= 8 /* AssertESNext */ | 1048576 /* ContainsObjectRest */; } - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 176 /* ArrayBindingPattern */: transformFlags |= 192 /* AssertES2015 */ | 8388608 /* ContainsBindingPattern */; - excludeFlags = 537396545 /* BindingPatternExcludes */; + excludeFlags = 940049729 /* BindingPatternExcludes */; break; case 177 /* BindingElement */: transformFlags |= 192 /* AssertES2015 */; @@ -22975,7 +22990,7 @@ var ts; transformFlags |= 3 /* AssertTypeScript */ | 4096 /* ContainsDecorators */; break; case 179 /* ObjectLiteralExpression */: - excludeFlags = 540087617 /* ObjectLiteralExcludes */; + excludeFlags = 942740801 /* ObjectLiteralExcludes */; if (subtreeFlags & 2097152 /* ContainsComputedPropertyName */) { // If an ObjectLiteralExpression contains a ComputedPropertyName, then it // is an ES6 node. @@ -22994,7 +23009,7 @@ var ts; break; case 178 /* ArrayLiteralExpression */: case 183 /* NewExpression */: - excludeFlags = 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + excludeFlags = 940049729 /* ArrayLiteralOrCallOrNewExcludes */; if (subtreeFlags & 524288 /* ContainsSpread */) { // If the this node contains a SpreadExpression, then it is an ES6 // node. @@ -23040,27 +23055,27 @@ var ts; case 182 /* CallExpression */: case 183 /* NewExpression */: case 178 /* ArrayLiteralExpression */: - return 537396545 /* ArrayLiteralOrCallOrNewExcludes */; + return 940049729 /* ArrayLiteralOrCallOrNewExcludes */; case 234 /* ModuleDeclaration */: - return 574674241 /* ModuleExcludes */; + return 977327425 /* ModuleExcludes */; case 147 /* Parameter */: - return 536872257 /* ParameterExcludes */; + return 939525441 /* ParameterExcludes */; case 188 /* ArrowFunction */: - return 601249089 /* ArrowFunctionExcludes */; + return 1003902273 /* ArrowFunctionExcludes */; case 187 /* FunctionExpression */: case 229 /* FunctionDeclaration */: - return 601281857 /* FunctionExcludes */; + return 1003935041 /* FunctionExcludes */; case 228 /* VariableDeclarationList */: - return 546309441 /* VariableDeclarationListExcludes */; + return 948962625 /* VariableDeclarationListExcludes */; case 230 /* ClassDeclaration */: case 200 /* ClassExpression */: - return 539358529 /* ClassExcludes */; + return 942011713 /* ClassExcludes */; case 153 /* Constructor */: - return 601015617 /* ConstructorExcludes */; + return 1003668801 /* ConstructorExcludes */; case 152 /* MethodDeclaration */: case 154 /* GetAccessor */: case 155 /* SetAccessor */: - return 601015617 /* MethodOrAccessorExcludes */; + return 1003668801 /* MethodOrAccessorExcludes */; case 119 /* AnyKeyword */: case 133 /* NumberKeyword */: case 130 /* NeverKeyword */: @@ -23079,14 +23094,23 @@ var ts; case 232 /* TypeAliasDeclaration */: return -3 /* TypeExcludes */; case 179 /* ObjectLiteralExpression */: - return 540087617 /* ObjectLiteralExcludes */; + return 942740801 /* ObjectLiteralExcludes */; case 264 /* CatchClause */: - return 537920833 /* CatchClauseExcludes */; + return 940574017 /* CatchClauseExcludes */; case 175 /* ObjectBindingPattern */: case 176 /* ArrayBindingPattern */: - return 537396545 /* BindingPatternExcludes */; + return 940049729 /* BindingPatternExcludes */; + case 185 /* TypeAssertionExpression */: + case 203 /* AsExpression */: + case 292 /* PartiallyEmittedExpression */: + case 186 /* ParenthesizedExpression */: + case 97 /* SuperKeyword */: + return 536872257 /* OuterExpressionExcludes */; + case 180 /* PropertyAccessExpression */: + case 181 /* ElementAccessExpression */: + return 671089985 /* PropertyAccessExcludes */; default: - return 536872257 /* NodeExcludes */; + return 939525441 /* NodeExcludes */; } } ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions; @@ -23926,7 +23950,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, /*onlyRecordFailures*/ false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -23940,6 +23966,40 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + /** + * This will be called on the successfully resolved path from `loadModuleFromFile`. + * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.) + * + * packageDirectory is the directory of the package itself. + * subModuleName is the path within the package. + * For `blah/node_modules/foo/index.d.ts` this is { packageDirectory: "foo", subModuleName: "" }. (Part before "/node_modules/" is ignored.) + * For `/node_modules/foo/bar.d.ts` this is { packageDirectory: "foo", subModuleName": "bar" }. + * For `/node_modules/@types/foo/bar/index.d.ts` this is { packageDirectory: "@types/foo", subModuleName: "bar" }. + */ + function parseNodeModuleFromPath(path) { + path = ts.normalizePath(path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = removeExtensionAndIndex(path.slice(indexAfterPackageName + 1)); + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function removeExtensionAndIndex(path) { + var noExtension = ts.removeFileExtension(path); + return noExtension === "index" ? "" : ts.removeSuffix(noExtension, "/index"); + } /* @internal */ function directoryProbablyExists(directoryName, host) { // if host does not support 'directoryExists' assume that directory will exist @@ -24030,13 +24090,18 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -24194,13 +24259,18 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + /* @internal */ + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { @@ -24392,6 +24462,11 @@ var ts; typeToTypeNode: nodeBuilder.typeToTypeNode, indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration, signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration, + symbolToEntityName: nodeBuilder.symbolToEntityName, + symbolToExpression: nodeBuilder.symbolToExpression, + symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations, + symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration, + typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration, getSymbolsInScope: function (location, meaning) { location = ts.getParseTreeNode(location); return location ? getSymbolsInScope(location, meaning) : []; @@ -24425,10 +24500,25 @@ var ts; typeToString: function (type, enclosingDeclaration, flags) { return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags); }, - getSymbolDisplayBuilder: getSymbolDisplayBuilder, - symbolToString: function (symbol, enclosingDeclaration, meaning) { - return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning); + symbolToString: function (symbol, enclosingDeclaration, meaning, flags) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags); }, + typePredicateToString: function (predicate, enclosingDeclaration, flags) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags); + }, + writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) { + return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer); + }, + writeType: function (type, enclosingDeclaration, flags, writer) { + return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) { + return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer); + }, + writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) { + return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer); + }, + getSymbolDisplayBuilder: getSymbolDisplayBuilder, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, getContextualType: function (node) { @@ -24525,7 +24615,12 @@ var ts; }, getJsxNamespace: function () { return ts.unescapeLeadingUnderscores(getJsxNamespace()); }, getAccessibleSymbolChain: getAccessibleSymbolChain, + getTypePredicateOfSignature: getTypePredicateOfSignature, resolveExternalModuleSymbol: resolveExternalModuleSymbol, + tryGetThisTypeAt: function (node) { + node = ts.getParseTreeNode(node); + return node && tryGetThisTypeAt(node); + }, }; var tupleTypes = []; var unionTypes = ts.createMap(); @@ -24746,14 +24841,13 @@ var ts; var comparableRelation = ts.createMap(); var identityRelation = ts.createMap(); var enumRelation = ts.createMap(); - // This is for caching the result of getSymbolDisplayBuilder. Do not access directly. - var _displayBuilder; 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) { @@ -24790,6 +24884,142 @@ var ts; var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor); initializeTypeChecker(); return checker; + /** + * @deprecated + */ + function getSymbolDisplayBuilder() { + return { + buildTypeDisplay: function (type, writer, enclosingDeclaration, flags) { + typeToString(type, enclosingDeclaration, flags, emitTextWriterWrapper(writer)); + }, + buildSymbolDisplay: function (symbol, writer, enclosingDeclaration, meaning, flags) { + symbolToString(symbol, enclosingDeclaration, meaning, flags | 4 /* AllowAnyNodeKind */, emitTextWriterWrapper(writer)); + }, + buildSignatureDisplay: function (signature, writer, enclosing, flags, kind) { + signatureToString(signature, enclosing, flags, kind, emitTextWriterWrapper(writer)); + }, + buildIndexSignatureDisplay: function (info, writer, kind, enclosing, flags) { + var sig = nodeBuilder.indexInfoToIndexSignatureDeclaration(info, kind, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, sig, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildParameterDisplay: function (symbol, writer, enclosing, flags) { + var node = nodeBuilder.symbolToParameterDeclaration(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplay: function (tp, writer, enclosing, flags) { + var node = nodeBuilder.typeParameterToDeclaration(tp, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 8192 /* OmitParameterModifiers */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildTypePredicateDisplay: function (predicate, writer, enclosing, flags) { + typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + }, + buildTypeParameterDisplayFromSymbol: function (symbol, writer, enclosing, flags) { + var nodes = nodeBuilder.symbolToTypeParameterDeclarations(symbol, enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeList(26896 /* TypeParameters */, nodes, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForParametersAndDelimiters: function (thisParameter, parameters, writer, enclosing, originalFlags) { + var printer = ts.createPrinter({ removeComments: true }); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */ | toNodeBuilderFlags(originalFlags); + var thisParameterArray = thisParameter ? [nodeBuilder.symbolToParameterDeclaration(thisParameter, enclosing, flags)] : []; + var params = ts.createNodeArray(thisParameterArray.concat(ts.map(parameters, function (param) { return nodeBuilder.symbolToParameterDeclaration(param, enclosing, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildDisplayForTypeParametersAndDelimiters: function (typeParameters, writer, enclosing, flags) { + var printer = ts.createPrinter({ removeComments: true }); + var args = ts.createNodeArray(ts.map(typeParameters, function (p) { return nodeBuilder.typeParameterToDeclaration(p, enclosing, toNodeBuilderFlags(flags)); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + }, + buildReturnTypeDisplay: function (signature, writer, enclosing, flags) { + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = getTypePredicateOfSignature(signature); + if (predicate) { + return typePredicateToString(predicate, enclosing, flags, emitTextWriterWrapper(writer)); + } + var node = nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosing, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); + var printer = ts.createPrinter({ removeComments: true }); + printer.writeNode(4 /* Unspecified */, node, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosing)), emitTextWriterWrapper(writer)); + } + }; + function emitTextWriterWrapper(underlying) { + return { + write: ts.noop, + writeTextOfNode: ts.noop, + writeLine: ts.noop, + increaseIndent: function () { + return underlying.increaseIndent(); + }, + decreaseIndent: function () { + return underlying.decreaseIndent(); + }, + getText: function () { + return ""; + }, + rawWrite: ts.noop, + writeLiteral: function (s) { + return underlying.writeStringLiteral(s); + }, + getTextPos: function () { + return 0; + }, + getLine: function () { + return 0; + }, + getColumn: function () { + return 0; + }, + getIndent: function () { + return 0; + }, + isAtStartOfLine: function () { + return false; + }, + clear: function () { + return underlying.clear(); + }, + writeKeyword: function (text) { + return underlying.writeKeyword(text); + }, + writeOperator: function (text) { + return underlying.writeOperator(text); + }, + writePunctuation: function (text) { + return underlying.writePunctuation(text); + }, + writeSpace: function (text) { + return underlying.writeSpace(text); + }, + writeStringLiteral: function (text) { + return underlying.writeStringLiteral(text); + }, + writeParameter: function (text) { + return underlying.writeParameter(text); + }, + writeProperty: function (text) { + return underlying.writeProperty(text); + }, + writeSymbol: function (text, symbol) { + return underlying.writeSymbol(text, symbol); + }, + trackSymbol: function (symbol, enclosing, meaning) { + return underlying.trackSymbol && underlying.trackSymbol(symbol, enclosing, meaning); + }, + reportInaccessibleThisError: function () { + return underlying.reportInaccessibleThisError && underlying.reportInaccessibleThisError(); + }, + reportPrivateInBaseOfClassExpression: function (name) { + return underlying.reportPrivateInBaseOfClassExpression && underlying.reportPrivateInBaseOfClassExpression(name); + }, + reportInaccessibleUniqueSymbolError: function () { + return underlying.reportInaccessibleUniqueSymbolError && underlying.reportInaccessibleUniqueSymbolError(); + } + }; + } + } function getJsxNamespace() { if (!_jsxNamespace) { _jsxNamespace = "React"; @@ -24805,10 +25035,12 @@ var ts; } return _jsxNamespace; } - function getEmitResolver(sourceFile, cancellationToken) { + function getEmitResolver(sourceFile, cancellationToken, ignoreDiagnostics) { // Ensure we have all the type information in place for this file so that all the // emitter questions of this resolver will return the right information. - getDiagnostics(sourceFile, cancellationToken); + if (!ignoreDiagnostics) { + getDiagnostics(sourceFile, cancellationToken); + } return emitResolver; } function error(location, message, arg0, arg1, arg2, arg3) { @@ -26024,7 +26256,7 @@ var ts; error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName); } else if (noImplicitAny && moduleNotFoundError) { - var errorInfo = !resolvedModule.isExternalLibraryImport ? undefined : ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference); + var errorInfo = resolvedModule.packageId && ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Try_npm_install_types_Slash_0_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, resolvedModule.packageId.name); errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type, moduleReference, resolvedModule.resolvedFileName); diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo)); } @@ -26431,6 +26663,10 @@ var ts; var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 793064 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false); return access.accessibility === 0 /* Accessible */; } + function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) { + var access = isSymbolAccessible(typeSymbol, enclosingDeclaration, 107455 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false); + return access.accessibility === 0 /* Accessible */; + } /** * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested * @@ -26558,97 +26794,131 @@ var ts; errorNode: firstIdentifier }; } - function writeKeyword(writer, kind) { - writer.writeKeyword(ts.tokenToString(kind)); + function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) { + if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; } + var nodeFlags = 3112960 /* IgnoreErrors */; + if (flags & 2 /* UseOnlyExternalAliasing */) { + nodeFlags |= 128 /* UseOnlyExternalAliasing */; + } + if (flags & 1 /* WriteTypeParametersOrArguments */) { + nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */; + } + var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName; + return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker); + function symbolToStringWorker(writer) { + var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function writePunctuation(writer, kind) { - writer.writePunctuation(ts.tokenToString(kind)); + function signatureToString(signature, enclosingDeclaration, flags, kind, writer) { + return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker); + function signatureToStringWorker(writer) { + var sigOutput; + if (flags & 262144 /* WriteArrowStyleSignature */) { + sigOutput = kind === 1 /* Construct */ ? 162 /* ConstructorType */ : 161 /* FunctionType */; + } + else { + sigOutput = kind === 1 /* Construct */ ? 157 /* ConstructSignature */ : 156 /* CallSignature */; + } + var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */); + var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, writer); + return writer; + } } - function writeSpace(writer) { - writer.writeSpace(" "); - } - function symbolToString(symbol, enclosingDeclaration, meaning) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning); - }); - } - function signatureToString(signature, enclosingDeclaration, flags, kind) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind); - }); - } - function typeToString(type, enclosingDeclaration, flags) { - var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | ts.NodeBuilderFlags.IgnoreErrors | ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName); + function typeToString(type, enclosingDeclaration, flags, writer) { + if (writer === void 0) { writer = ts.createTextWriter(""); } + var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */, writer); ts.Debug.assert(typeNode !== undefined, "should always get typenode"); var options = { removeComments: true }; - var writer = ts.createTextWriter(""); var printer = ts.createPrinter(options); var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer); var result = writer.getText(); - var maxLength = compilerOptions.noErrorTruncation || flags & 8 /* NoTruncation */ ? undefined : 100; - if (maxLength && result.length >= maxLength) { + var maxLength = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */ ? undefined : 100; + if (maxLength && result && result.length >= maxLength) { return result.substr(0, maxLength - "...".length) + "..."; } return result; - function toNodeBuilderFlags(flags) { - var result = ts.NodeBuilderFlags.None; - if (!flags) { - return result; - } - if (flags & 8 /* NoTruncation */) { - result |= ts.NodeBuilderFlags.NoTruncation; - } - if (flags & 256 /* UseFullyQualifiedType */) { - result |= ts.NodeBuilderFlags.UseFullyQualifiedType; - } - if (flags & 4096 /* SuppressAnyReturnType */) { - result |= ts.NodeBuilderFlags.SuppressAnyReturnType; - } - if (flags & 1 /* WriteArrayAsGenericType */) { - result |= ts.NodeBuilderFlags.WriteArrayAsGenericType; - } - if (flags & 64 /* WriteTypeArgumentsOfSignature */) { - result |= ts.NodeBuilderFlags.WriteTypeArgumentsOfSignature; - } - return result; - } + } + function toNodeBuilderFlags(flags) { + return flags & 9469295 /* NodeBuilderFlagsMask */; } function createNodeBuilder() { return { - typeToTypeNode: function (type, enclosingDeclaration, flags) { + typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = typeToTypeNodeHelper(type, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags) { + indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; }, - signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags) { + signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) { ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); - var context = createNodeBuilderContext(enclosingDeclaration, flags); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); var resultingNode = signatureToSignatureDeclarationHelper(signature, kind, context); var result = context.encounteredError ? undefined : resultingNode; return result; - } + }, + symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToExpression(symbol, context, meaning); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParametersToTypeParameterDeclarations(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = symbolToParameterDeclaration(symbol, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, + typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) { + ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0); + var context = createNodeBuilderContext(enclosingDeclaration, flags, tracker); + var resultingNode = typeParameterToDeclaration(parameter, context); + var result = context.encounteredError ? undefined : resultingNode; + return result; + }, }; - function createNodeBuilderContext(enclosingDeclaration, flags) { + function createNodeBuilderContext(enclosingDeclaration, flags, tracker) { return { enclosingDeclaration: enclosingDeclaration, flags: flags, + tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop }, encounteredError: false, symbolStack: undefined }; } function typeToTypeNodeHelper(type, context) { - var inTypeAlias = context.flags & ts.NodeBuilderFlags.InTypeAlias; - context.flags &= ~ts.NodeBuilderFlags.InTypeAlias; + var inTypeAlias = context.flags & 8388608 /* InTypeAlias */; + context.flags &= ~8388608 /* InTypeAlias */; if (!type) { context.encounteredError = true; return undefined; @@ -26685,6 +26955,11 @@ var ts; return type.intrinsicName === "true" ? ts.createTrue() : ts.createFalse(); } if (type.flags & 1024 /* UniqueESSymbol */) { + if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) { + if (context.tracker.reportInaccessibleUniqueSymbolError) { + context.tracker.reportInaccessibleUniqueSymbolError(); + } + } return ts.createTypeOperatorNode(140 /* UniqueKeyword */, ts.createKeywordTypeNode(137 /* SymbolKeyword */)); } if (type.flags & 2048 /* Void */) { @@ -26706,10 +26981,13 @@ var ts; return ts.createKeywordTypeNode(134 /* ObjectKeyword */); } if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (context.flags & ts.NodeBuilderFlags.InObjectTypeLiteral) { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowThisInObjectLiteral)) { + if (context.flags & 4194304 /* InObjectTypeLiteral */) { + if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) { context.encounteredError = true; } + if (context.tracker.reportInaccessibleThisError) { + context.tracker.reportInaccessibleThisError(); + } } return ts.createThis(); } @@ -26723,7 +27001,7 @@ var ts; // 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 && isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration)) { + 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); @@ -26736,7 +27014,7 @@ var ts; return unionOrIntersectionTypeNode; } else { - if (!context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowEmptyUnionOrIntersection)) { + if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) { context.encounteredError = true; } return undefined; @@ -26762,7 +27040,7 @@ var ts; ts.Debug.assert(!!(type.flags & 65536 /* Object */)); var readonlyToken = type.declaration && type.declaration.readonlyToken ? ts.createToken(131 /* ReadonlyKeyword */) : undefined; var questionToken = type.declaration && type.declaration.questionToken ? ts.createToken(55 /* QuestionToken */) : undefined; - var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context); + var typeParameterNode = typeParameterToDeclaration(getTypeParameterFromMappedType(type), context, getConstraintTypeFromMappedType(type)); var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context); var mappedTypeNode = ts.createMappedTypeNode(readonlyToken, typeParameterNode, questionToken, templateTypeNode); return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */); @@ -26771,7 +27049,7 @@ var ts; var symbol = type.symbol; if (symbol) { // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) || + if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) || symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) || shouldWriteTypeOfFunctionSymbol()) { return createTypeQueryNodeFromSymbol(symbol, 107455 /* Value */); @@ -26794,10 +27072,16 @@ var ts; if (!context.symbolStack) { context.symbolStack = []; } - context.symbolStack.push(symbol); - var result = createTypeNodeFromObjectType(type); - context.symbolStack.pop(); - return result; + 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; + } } } else { @@ -26814,7 +27098,8 @@ var ts; })); if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { // typeof is allowed only for static/non local functions - return ts.contains(context.symbolStack, symbol); // it is type of the symbol uses itself recursively + return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ts.contains(context.symbolStack, symbol)) && // 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 } } } @@ -26839,11 +27124,11 @@ var ts; } } var savedFlags = context.flags; - context.flags |= ts.NodeBuilderFlags.InObjectTypeLiteral; + context.flags |= 4194304 /* InObjectTypeLiteral */; var members = createTypeNodesFromResolvedType(resolved); context.flags = savedFlags; var typeLiteralNode = ts.createTypeLiteralNode(members); - return ts.setEmitFlags(typeLiteralNode, 1 /* SingleLine */); + return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */); } function createTypeQueryNodeFromSymbol(symbol, symbolFlags) { var entityName = symbolToName(symbol, context, symbolFlags, /*expectsIdentifier*/ false); @@ -26857,7 +27142,7 @@ var ts; function typeReferenceToTypeNode(type) { var typeArguments = type.typeArguments || ts.emptyArray; if (type.target === globalArrayType) { - if (context.flags & ts.NodeBuilderFlags.WriteArrayAsGenericType) { + if (context.flags & 2 /* WriteArrayAsGenericType */) { var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context); return ts.createTypeReferenceNode("Array", [typeArgumentNode]); } @@ -26871,12 +27156,17 @@ var ts; return ts.createTupleTypeNode(tupleConstituentNodes); } } - if (context.encounteredError || (context.flags & ts.NodeBuilderFlags.AllowEmptyTuple)) { + if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) { return ts.createTupleTypeNode([]); } context.encounteredError = true; return undefined; } + else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ && + type.symbol.valueDeclaration && + type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { + return createAnonymousTypeNode(type); + } else { var outerTypeParameters = type.target.outerTypeParameters; var i = 0; @@ -26969,9 +27259,24 @@ var ts; } for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) { var propertySymbol = properties_1[_d]; + if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) { + if (propertySymbol.flags & 4194304 /* Prototype */) { + continue; + } + if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) { + context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName)); + } + } var propertyType = ts.getCheckFlags(propertySymbol) & 2048 /* ReverseMapped */ ? anyType : getTypeOfSymbol(propertySymbol); var saveEnclosingDeclaration = context.enclosingDeclaration; context.enclosingDeclaration = undefined; + if (ts.getCheckFlags(propertySymbol) & 1024 /* Late */) { + var decl = ts.firstOrUndefined(propertySymbol.declarations); + var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); + if (name && context.tracker.trackSymbol) { + context.tracker.trackSymbol(name, saveEnclosingDeclaration, 107455 /* Value */); + } + } var propertyName = symbolToName(propertySymbol, context, 107455 /* Value */, /*expectsIdentifier*/ true); context.enclosingDeclaration = saveEnclosingDeclaration; var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.createToken(55 /* QuestionToken */) : undefined; @@ -27018,12 +27323,22 @@ var ts; /*dotDotDotToken*/ undefined, name, /*questionToken*/ undefined, indexerTypeNode, /*initializer*/ undefined); - var typeNode = typeToTypeNodeHelper(indexInfo.type, context); + var typeNode = indexInfo.type ? typeToTypeNodeHelper(indexInfo.type, context) : typeToTypeNodeHelper(anyType, context); + if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) { + context.encounteredError = true; + } return ts.createIndexSignature( /*decorators*/ undefined, indexInfo.isReadonly ? [ts.createToken(131 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode); } function signatureToSignatureDeclarationHelper(signature, kind, context) { - var typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + var typeParameters; + var typeArguments; + if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) { + typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); }); + } + else { + typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); }); + } var parameters = signature.parameters.map(function (parameter) { return symbolToParameterDeclaration(parameter, context); }); if (signature.thisParameter) { var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context); @@ -27042,7 +27357,7 @@ var ts; var returnType = getReturnTypeOfSignature(signature); returnTypeNode = returnType && typeToTypeNodeHelper(returnType, context); } - if (context.flags & ts.NodeBuilderFlags.SuppressAnyReturnType) { + if (context.flags & 256 /* SuppressAnyReturnType */) { if (returnTypeNode && returnTypeNode.kind === 119 /* AnyKeyword */) { returnTypeNode = undefined; } @@ -27050,14 +27365,17 @@ var ts; else if (!returnTypeNode) { returnTypeNode = ts.createKeywordTypeNode(119 /* AnyKeyword */); } - return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode); + return ts.createSignatureDeclaration(kind, typeParameters, parameters, returnTypeNode, typeArguments); } - function typeParameterToDeclaration(type, context) { + function typeParameterToDeclaration(type, context, constraint) { + if (constraint === void 0) { constraint = getConstraintFromTypeParameter(type); } + 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, 793064 /* Type */, /*expectsIdentifier*/ true); - var constraint = getConstraintFromTypeParameter(type); var constraintNode = constraint && typeToTypeNodeHelper(constraint, context); var defaultParameter = getDefaultFromTypeParameter(type); var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context); + context.flags = savedContextFlags; return ts.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode); } function symbolToParameterDeclaration(parameterSymbol, context) { @@ -27068,7 +27386,7 @@ var ts; parameterType = getOptionalType(parameterType); } var parameterTypeNode = typeToTypeNodeHelper(parameterType, context); - var modifiers = parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); + var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && parameterDeclaration && parameterDeclaration.modifiers && parameterDeclaration.modifiers.map(ts.getSynthesizedClone); var dotDotDotToken = !parameterDeclaration || ts.isRestParameter(parameterDeclaration) ? ts.createToken(24 /* DotDotDotToken */) : undefined; var name = parameterDeclaration ? parameterDeclaration.name ? @@ -27094,47 +27412,22 @@ var ts; } } } - function symbolToName(symbol, context, meaning, expectsIdentifier) { + function lookupSymbolChain(symbol, context, meaning) { + 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; var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - if (!isTypeParameter && (context.enclosingDeclaration || context.flags & ts.NodeBuilderFlags.UseFullyQualifiedType)) { + if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */)) { chain = getSymbolChain(symbol, meaning, /*endOfChain*/ true); ts.Debug.assert(chain && chain.length > 0); } else { chain = [symbol]; } - if (expectsIdentifier && chain.length !== 1 - && !context.encounteredError - && !(context.flags & ts.NodeBuilderFlags.AllowQualifedNameInPlaceOfIdentifier)) { - context.encounteredError = true; - } - return createEntityNameFromSymbolChain(chain, chain.length - 1); - function createEntityNameFromSymbolChain(chain, index) { - ts.Debug.assert(chain && 0 <= index && index < chain.length); - var symbol = chain[index]; - var typeParameterNodes; - if (context.flags & ts.NodeBuilderFlags.WriteTypeParametersInQualifiedName && index > 0) { - var parentSymbol = chain[index - 1]; - var typeParameters = void 0; - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - typeParameters = getTypeParametersOfClassOrInterface(parentSymbol); - } - else { - var targetSymbol = getTargetSymbol(parentSymbol); - if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { - typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol); - } - } - typeParameterNodes = mapToTypeNodes(typeParameters, context); - } - var identifier = ts.setEmitFlags(ts.createIdentifier(getNameOfSymbolAsWritten(symbol, context), typeParameterNodes), 16777216 /* NoAsciiEscaping */); - return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; - } + return chain; /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ function getSymbolChain(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false); + var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */)); var parentSymbol; if (!accessibleSymbolChain || needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { @@ -27162,11 +27455,93 @@ var ts; } } } + function typeParametersToTypeParameterDeclarations(symbol, context) { + var typeParameterNodes; + var targetSymbol = getTargetSymbol(symbol); + if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) { + typeParameterNodes = ts.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); })); + } + return typeParameterNodes; + } + function lookupTypeParameterNodes(chain, index, context) { + ts.Debug.assert(chain && 0 <= index && index < chain.length); + var symbol = chain[index]; + var typeParameterNodes; + if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) { + var parentSymbol = symbol; + var nextSymbol = chain[index + 1]; + if (ts.getCheckFlags(nextSymbol) & 1 /* Instantiated */) { + var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); + typeParameterNodes = mapToTypeNodes(ts.map(params, nextSymbol.mapper), context); + } + else { + typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context); + } + } + return typeParameterNodes; + } + function symbolToName(symbol, context, meaning, expectsIdentifier) { + var chain = lookupSymbolChain(symbol, context, meaning); + if (expectsIdentifier && chain.length !== 1 + && !context.encounteredError + && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) { + context.encounteredError = true; + } + return createEntityNameFromSymbolChain(chain, chain.length - 1); + function createEntityNameFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier; + } + } + function symbolToExpression(symbol, context, meaning) { + var chain = lookupSymbolChain(symbol, context, meaning); + return createExpressionFromSymbolChain(chain, chain.length - 1); + function createExpressionFromSymbolChain(chain, index) { + var typeParameterNodes = lookupTypeParameterNodes(chain, index, context); + var symbol = chain[index]; + var symbolName = getNameOfSymbolAsWritten(symbol, context); + var firstChar = symbolName.charCodeAt(0); + var canUsePropertyAccess = ts.isIdentifierStart(firstChar, languageVersion); + if (index === 0 || canUsePropertyAccess) { + var identifier = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + identifier.symbol = symbol; + return index > 0 ? ts.createPropertyAccess(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier; + } + else { + if (firstChar === 91 /* openBracket */) { + symbolName = symbolName.substring(1, symbolName.length - 1); + firstChar = symbolName.charCodeAt(0); + } + var expression = void 0; + if (ts.isSingleOrDoubleQuote(firstChar)) { + expression = ts.createLiteral(symbolName.substring(1, symbolName.length - 1).replace(/\\./g, function (s) { return s.substring(1); })); + expression.singleQuote = firstChar === 39 /* singleQuote */; + } + else if (("" + +symbolName) === symbolName) { + expression = ts.createLiteral(+symbolName); + } + if (!expression) { + expression = ts.setEmitFlags(ts.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */); + expression.symbol = symbol; + } + return ts.createElementAccess(createExpressionFromSymbolChain(chain, index - 1), expression); + } + } + } } - function typePredicateToString(typePredicate, enclosingDeclaration, flags) { - return ts.usingSingleLineStringWriter(function (writer) { - getSymbolDisplayBuilder().buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags); - }); + function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) { + return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker); + function typePredicateToStringWorker(writer) { + var predicate = ts.createTypePredicateNode(typePredicate.kind === 1 /* Identifier */ ? ts.createIdentifier(typePredicate.parameterName) : ts.createThisTypeNode(), nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 3112960 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */)); + var printer = ts.createPrinter({ removeComments: true }); + var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration); + printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer); + return writer; + } } function formatUnionTypes(types) { var result = []; @@ -27229,6 +27604,9 @@ var ts; * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`. */ function getNameOfSymbolAsWritten(symbol, context) { + if (context && context.flags & 4 /* WriteDefaultSymbolWithoutName */ && symbol.escapedName === "default" /* Default */) { + return "default"; + } if (symbol.declarations && symbol.declarations.length) { var declaration = symbol.declarations[0]; var name = ts.getNameOfDeclaration(declaration); @@ -27238,7 +27616,7 @@ var ts; if (declaration.parent && declaration.parent.kind === 227 /* VariableDeclaration */) { return ts.declarationNameToString(declaration.parent.name); } - if (context && !context.encounteredError && !(context.flags & ts.NodeBuilderFlags.AllowAnonymousIdentifier)) { + if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) { context.encounteredError = true; } switch (declaration.kind) { @@ -27257,736 +27635,6 @@ var ts; } return ts.symbolName(symbol); } - function getSymbolDisplayBuilder() { - /** - * Writes only the name of the symbol out to the writer. Uses the original source text - * for the name of the symbol if it is available to match how the user wrote the name. - */ - function appendSymbolNameOnly(symbol, writer) { - writer.writeSymbol(getNameOfSymbolAsWritten(symbol), symbol); - } - /** - * Writes a property access or element access with the name of the symbol out to the writer. - * Uses the original source text for the name of the symbol if it is available to match how the user wrote the name, - * ensuring that any names written with literals use element accesses. - */ - function appendPropertyOrElementAccessForSymbol(symbol, writer) { - var symbolName = symbol.escapedName === "default" /* Default */ ? "default" /* Default */ : getNameOfSymbolAsWritten(symbol); - var firstChar = symbolName.charCodeAt(0); - var needsElementAccess = !ts.isIdentifierStart(firstChar, languageVersion); - if (needsElementAccess) { - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - } - if (ts.isSingleOrDoubleQuote(firstChar)) { - writer.writeStringLiteral(symbolName); - } - else { - writer.writeSymbol(symbolName, symbol); - } - if (firstChar !== 91 /* openBracket */) { - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - else { - writePunctuation(writer, 23 /* DotToken */); - writer.writeSymbol(symbolName, symbol); - } - } - /** - * Enclosing declaration is optional when we don't want to get qualified name in the enclosing declaration scope - * Meaning needs to be specified if the enclosing declaration is given - */ - function buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags, typeFlags) { - var parentSymbol; - function appendParentTypeArgumentsAndSymbolName(symbol) { - if (parentSymbol) { - // Write type arguments of instantiated class/interface here - if (flags & 1 /* WriteTypeParametersOrArguments */) { - if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) { - var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol); - buildDisplayForTypeArgumentsAndDelimiters(params, symbol.mapper, writer, enclosingDeclaration); - } - else { - buildTypeParameterDisplayFromSymbol(parentSymbol, writer, enclosingDeclaration); - } - } - appendPropertyOrElementAccessForSymbol(symbol, writer); - } - else { - appendSymbolNameOnly(symbol, writer); - } - parentSymbol = symbol; - } - // Let the writer know we just wrote out a symbol. The declaration emitter writer uses - // this to determine if an import it has previously seen (and not written out) needs - // to be written to the file once the walk of the tree is complete. - // - // NOTE(cyrusn): This approach feels somewhat unfortunate. A simple pass over the tree - // up front (for example, during checking) could determine if we need to emit the imports - // and we could then access that data during declaration emit. - writer.trackSymbol(symbol, enclosingDeclaration, meaning); - /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */ - function walkSymbol(symbol, meaning, endOfChain) { - var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, !!(flags & 2 /* UseOnlyExternalAliasing */)); - if (!accessibleSymbolChain || - needsQualification(accessibleSymbolChain[0], enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) { - // Go up and add our parent. - var parent = getParentOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol); - if (parent) { - walkSymbol(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false); - } - } - if (accessibleSymbolChain) { - for (var _i = 0, accessibleSymbolChain_1 = accessibleSymbolChain; _i < accessibleSymbolChain_1.length; _i++) { - var accessibleSymbol = accessibleSymbolChain_1[_i]; - appendParentTypeArgumentsAndSymbolName(accessibleSymbol); - } - } - else if ( - // 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)) && - // If a parent symbol is an anonymous type, don't write it. - !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - // Get qualified name if the symbol is not a type parameter - // and there is an enclosing declaration or we specifically - // asked for it - var isTypeParameter = symbol.flags & 262144 /* TypeParameter */; - var typeFormatFlag = 256 /* UseFullyQualifiedType */ & typeFlags; - if (!isTypeParameter && (enclosingDeclaration || typeFormatFlag)) { - walkSymbol(symbol, meaning, /*endOfChain*/ true); - } - else { - appendParentTypeArgumentsAndSymbolName(symbol); - } - } - function buildTypeDisplay(type, writer, enclosingDeclaration, globalFlags, symbolStack) { - var globalFlagsToPass = globalFlags & (32 /* WriteOwnNameForAnyLike */ | 16384 /* WriteClassExpressionAsTypeLiteral */); - var inObjectTypeLiteral = false; - return writeType(type, globalFlags); - function writeType(type, flags) { - var nextFlags = flags & ~1024 /* InTypeAlias */; - // Write undefined/null type as any - if (type.flags & 33585807 /* Intrinsic */) { - // Special handling for unknown / resolving types, they should show up as any and not unknown or __resolving - writer.writeKeyword(!(globalFlags & 32 /* WriteOwnNameForAnyLike */) && isTypeAny(type) - ? "any" - : type.intrinsicName); - } - else if (type.flags & 32768 /* TypeParameter */ && type.isThisType) { - if (inObjectTypeLiteral) { - writer.reportInaccessibleThisError(); - } - writer.writeKeyword("this"); - } - else if (ts.getObjectFlags(type) & 4 /* Reference */) { - writeTypeReference(type, nextFlags); - } - else if (type.flags & 256 /* EnumLiteral */ && !(type.flags & 131072 /* Union */)) { - var parent = getParentOfSymbol(type.symbol); - buildSymbolDisplay(parent, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - // In a literal enum type with a single member E { A }, E and E.A denote the - // same type. We always display this type simply as E. - if (getDeclaredTypeOfSymbol(parent) !== type) { - writePunctuation(writer, 23 /* DotToken */); - appendSymbolNameOnly(type.symbol, writer); - } - } - else if (ts.getObjectFlags(type) & 3 /* ClassOrInterface */ || type.flags & (272 /* EnumLike */ | 32768 /* TypeParameter */)) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(type.symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, nextFlags); - } - else if (!(flags & 1024 /* InTypeAlias */) && type.aliasSymbol && - ((flags & 65536 /* UseAliasDefinedOutsideCurrentScope */) || isTypeSymbolAccessible(type.aliasSymbol, enclosingDeclaration))) { - var typeArguments = type.aliasTypeArguments; - writeSymbolTypeReference(type.aliasSymbol, typeArguments, 0, ts.length(typeArguments), nextFlags); - } - else if (type.flags & 393216 /* UnionOrIntersection */) { - writeUnionOrIntersectionType(type, nextFlags); - } - else if (ts.getObjectFlags(type) & (16 /* Anonymous */ | 32 /* Mapped */)) { - writeAnonymousType(type, nextFlags); - } - else if (type.flags & 1024 /* UniqueESSymbol */) { - if (flags & 131072 /* AllowUniqueESSymbolType */) { - writeKeyword(writer, 140 /* UniqueKeyword */); - writeSpace(writer); - } - else { - writer.reportInaccessibleUniqueSymbolError(); - } - writeKeyword(writer, 137 /* SymbolKeyword */); - } - else if (type.flags & 96 /* StringOrNumberLiteral */) { - writer.writeStringLiteral(literalTypeToString(type)); - } - else if (type.flags & 524288 /* Index */) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writer.writeKeyword("keyof"); - writeSpace(writer); - writeType(type.type, 128 /* InElementType */); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - else if (type.flags & 1048576 /* IndexedAccess */) { - writeType(type.objectType, 128 /* InElementType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writeType(type.indexType, 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else { - // Should never get here - // { ... } - writePunctuation(writer, 17 /* OpenBraceToken */); - writeSpace(writer); - writePunctuation(writer, 24 /* DotDotDotToken */); - writeSpace(writer); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function writeTypeList(types, delimiter) { - for (var i = 0; i < types.length; i++) { - if (i > 0) { - if (delimiter !== 26 /* CommaToken */) { - writeSpace(writer); - } - writePunctuation(writer, delimiter); - writeSpace(writer); - } - writeType(types[i], delimiter === 26 /* CommaToken */ ? 0 /* None */ : 128 /* InElementType */); - } - } - function writeSymbolTypeReference(symbol, typeArguments, pos, end, flags) { - // Unnamed function expressions and arrow functions have reserved names that we don't want to display - if (symbol.flags & 32 /* Class */ || !isReservedMemberName(symbol.escapedName)) { - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - if (pos < end) { - writePunctuation(writer, 27 /* LessThanToken */); - writeType(typeArguments[pos], 512 /* InFirstTypeArgument */); - pos++; - while (pos < end) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - writeType(typeArguments[pos], 0 /* None */); - pos++; - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function writeTypeReference(type, flags) { - var typeArguments = type.typeArguments || ts.emptyArray; - if (type.target === globalArrayType && !(flags & 1 /* WriteArrayAsGenericType */)) { - writeType(typeArguments[0], 128 /* InElementType */ | 32768 /* InArrayType */); - writePunctuation(writer, 21 /* OpenBracketToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (type.target.objectFlags & 8 /* Tuple */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - writeTypeList(type.typeArguments.slice(0, getTypeReferenceArity(type)), 26 /* CommaToken */); - writePunctuation(writer, 22 /* CloseBracketToken */); - } - else if (flags & 16384 /* WriteClassExpressionAsTypeLiteral */ && - type.symbol.valueDeclaration && - type.symbol.valueDeclaration.kind === 200 /* ClassExpression */) { - writeAnonymousType(type, flags); - } - else { - // Write the type reference in the format f.g.C where A and B are type arguments - // for outer type parameters, and f and g are the respective declaring containers of those - // type parameters. - var outerTypeParameters = type.target.outerTypeParameters; - var i = 0; - if (outerTypeParameters) { - var length_2 = outerTypeParameters.length; - while (i < length_2) { - // Find group of type arguments for type parameters with the same declaring container. - var start = i; - var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]); - do { - i++; - } while (i < length_2 && 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)) { - writeSymbolTypeReference(parent, typeArguments, start, i, flags); - writePunctuation(writer, 23 /* DotToken */); - } - } - } - var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length; - writeSymbolTypeReference(type.symbol, typeArguments, i, typeParameterCount, flags); - } - } - function writeUnionOrIntersectionType(type, flags) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - if (type.flags & 131072 /* Union */) { - writeTypeList(formatUnionTypes(type.types), 49 /* BarToken */); - } - else { - writeTypeList(type.types, 48 /* AmpersandToken */); - } - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writeAnonymousType(type, flags) { - var symbol = type.symbol; - if (symbol) { - // Always use 'typeof T' for type of class, enum, and module objects - if (symbol.flags & 32 /* Class */ && - !getBaseTypeVariableOfClass(symbol) && - !(symbol.valueDeclaration.kind === 200 /* ClassExpression */ && flags & 16384 /* WriteClassExpressionAsTypeLiteral */) || - symbol.flags & (384 /* Enum */ | 512 /* ValueModule */)) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (shouldWriteTypeOfFunctionSymbol()) { - writeTypeOfSymbol(type.symbol, flags); - } - else if (ts.contains(symbolStack, symbol)) { - // If type is an anonymous type literal in a type alias declaration, use type alias name - var typeAlias = getTypeAliasForTypeLiteral(type); - if (typeAlias) { - // The specified symbol flags need to be reinterpreted as type flags - buildSymbolDisplay(typeAlias, writer, enclosingDeclaration, 793064 /* Type */, 0 /* None */, flags); - } - else { - // Recursive usage, use any - writeKeyword(writer, 119 /* AnyKeyword */); - } - } - 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 - // However, in case of class expressions, we want to write both the static side and the instance side. - // We skip adding the static side so that the instance side has a chance to be written - // before checking for circular references. - if (!symbolStack) { - symbolStack = []; - } - var isConstructorObject = type.objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */; - if (isConstructorObject) { - writeLiteralType(type, flags); - } - else { - symbolStack.push(symbol); - writeLiteralType(type, flags); - symbolStack.pop(); - } - } - } - else { - // Anonymous types with no symbol are never circular - writeLiteralType(type, flags); - } - function shouldWriteTypeOfFunctionSymbol() { - var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method - ts.some(symbol.declarations, function (declaration) { return ts.hasModifier(declaration, 32 /* Static */); }); - var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) && - (symbol.parent || // is exported function symbol - ts.some(symbol.declarations, function (declaration) { - return declaration.parent.kind === 269 /* SourceFile */ || declaration.parent.kind === 235 /* ModuleBlock */; - })); - if (isStaticMethodSymbol || isNonLocalFunctionSymbol) { - // typeof is allowed only for static/non local functions - return !!(flags & 4 /* UseTypeOfFunction */) || // use typeof if format flags specify it - ts.contains(symbolStack, symbol); // it is type of the symbol uses itself recursively - } - } - } - function writeTypeOfSymbol(symbol, typeFormatFlags) { - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 103 /* TypeOfKeyword */); - writeSpace(writer); - buildSymbolDisplay(symbol, writer, enclosingDeclaration, 107455 /* Value */, 0 /* None */, typeFormatFlags); - if (typeFormatFlags & 32768 /* InArrayType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - } - function writePropertyWithModifiers(prop) { - if (isReadonlySymbol(prop)) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - if (ts.getCheckFlags(prop) & 1024 /* Late */) { - var decl = ts.firstOrUndefined(prop.declarations); - var name = hasLateBindableName(decl) && resolveEntityName(decl.name.expression, 107455 /* Value */); - if (name) { - writer.trackSymbol(name, enclosingDeclaration, 107455 /* Value */); - } - } - buildSymbolDisplay(prop, writer); - if (prop.flags & 16777216 /* Optional */) { - writePunctuation(writer, 55 /* QuestionToken */); - } - } - function shouldAddParenthesisAroundFunctionType(callSignature, flags) { - if (flags & 128 /* InElementType */) { - return true; - } - else if (flags & 512 /* InFirstTypeArgument */) { - // Add parenthesis around function type for the first type argument to avoid ambiguity - var typeParameters = callSignature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */) ? - callSignature.target.typeParameters : callSignature.typeParameters; - return typeParameters && typeParameters.length !== 0; - } - return false; - } - function writeLiteralType(type, flags) { - if (isGenericMappedType(type)) { - writeMappedType(type); - return; - } - var resolved = resolveStructuredTypeMembers(type); - if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) { - if (!resolved.callSignatures.length && !resolved.constructSignatures.length) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writePunctuation(writer, 18 /* CloseBraceToken */); - return; - } - if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) { - var parenthesizeSignature = shouldAddParenthesisAroundFunctionType(resolved.callSignatures[0], flags); - if (parenthesizeSignature) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - buildSignatureDisplay(resolved.callSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (parenthesizeSignature) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) { - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 19 /* OpenParenToken */); - } - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - buildSignatureDisplay(resolved.constructSignatures[0], writer, enclosingDeclaration, globalFlagsToPass | 16 /* WriteArrowStyleSignature */, /*kind*/ undefined, symbolStack); - if (flags & 128 /* InElementType */) { - writePunctuation(writer, 20 /* CloseParenToken */); - } - return; - } - } - var saveInObjectTypeLiteral = inObjectTypeLiteral; - inObjectTypeLiteral = true; - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - writeObjectLiteralType(resolved); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - inObjectTypeLiteral = saveInObjectTypeLiteral; - } - function writeObjectLiteralType(resolved) { - for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) { - var signature = _a[_i]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) { - var signature = _c[_b]; - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, 1 /* Construct */, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - var stringIndexInfo = resolved.objectFlags & 2048 /* ReverseMapped */ && resolved.stringIndexInfo ? - createIndexInfo(anyType, resolved.stringIndexInfo.isReadonly, resolved.stringIndexInfo.declaration) : - resolved.stringIndexInfo; - buildIndexSignatureDisplay(stringIndexInfo, writer, 0 /* String */, enclosingDeclaration, globalFlags, symbolStack); - buildIndexSignatureDisplay(resolved.numberIndexInfo, writer, 1 /* Number */, enclosingDeclaration, globalFlags, symbolStack); - for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) { - var p = _e[_d]; - if (globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */) { - if (p.flags & 4194304 /* Prototype */) { - continue; - } - if (ts.getDeclarationModifierFlagsFromSymbol(p) & (8 /* Private */ | 16 /* Protected */)) { - writer.reportPrivateInBaseOfClassExpression(ts.symbolName(p)); - } - } - var t = ts.getCheckFlags(p) & 2048 /* ReverseMapped */ ? anyType : getTypeOfSymbol(p); - if (p.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(t).length) { - var signatures = getSignaturesOfType(t, 0 /* Call */); - for (var _f = 0, signatures_2 = signatures; _f < signatures_2.length; _f++) { - var signature = signatures_2[_f]; - writePropertyWithModifiers(p); - buildSignatureDisplay(signature, writer, enclosingDeclaration, globalFlagsToPass, /*kind*/ undefined, symbolStack); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - else { - writePropertyWithModifiers(p); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(t, globalFlags & 16384 /* WriteClassExpressionAsTypeLiteral */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - } - function writeMappedType(type) { - writePunctuation(writer, 17 /* OpenBraceToken */); - writer.writeLine(); - writer.increaseIndent(); - if (type.declaration.readonlyToken) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - appendSymbolNameOnly(getTypeParameterFromMappedType(type).symbol, writer); - writeSpace(writer); - writeKeyword(writer, 92 /* InKeyword */); - writeSpace(writer); - writeType(getConstraintTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 22 /* CloseBracketToken */); - if (type.declaration.questionToken) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - writeType(getTemplateTypeFromMappedType(type), 0 /* None */); - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - writer.decreaseIndent(); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - } - function buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration, flags) { - var targetSymbol = getTargetSymbol(symbol); - if (targetSymbol.flags & 32 /* Class */ || targetSymbol.flags & 64 /* Interface */ || targetSymbol.flags & 524288 /* TypeAlias */) { - buildDisplayForTypeParametersAndDelimiters(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), writer, enclosingDeclaration, flags); - } - } - function buildTypeParameterDisplay(tp, writer, enclosingDeclaration, flags, symbolStack) { - appendSymbolNameOnly(tp.symbol, writer); - var constraint = getConstraintOfTypeParameter(tp); - if (constraint) { - writeSpace(writer); - writeKeyword(writer, 85 /* ExtendsKeyword */); - writeSpace(writer); - buildTypeDisplay(constraint, writer, enclosingDeclaration, flags, symbolStack); - } - var defaultType = getDefaultFromTypeParameter(tp); - if (defaultType) { - writeSpace(writer); - writePunctuation(writer, 58 /* EqualsToken */); - writeSpace(writer); - buildTypeDisplay(defaultType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack) { - var parameterNode = p.valueDeclaration; - if (parameterNode ? ts.isRestParameter(parameterNode) : isTransientSymbol(p) && p.isRestParameter) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - if (parameterNode && ts.isBindingPattern(parameterNode.name)) { - buildBindingPatternDisplay(parameterNode.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - appendSymbolNameOnly(p, writer); - } - if (parameterNode && isOptionalParameter(parameterNode)) { - writePunctuation(writer, 55 /* QuestionToken */); - } - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - var type = getTypeOfSymbol(p); - if (parameterNode && isRequiredInitializedParameter(parameterNode)) { - type = getOptionalType(type); - } - buildTypeDisplay(type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildBindingPatternDisplay(bindingPattern, writer, enclosingDeclaration, flags, symbolStack) { - // We have to explicitly emit square bracket and bracket because these tokens are not stored inside the node. - if (bindingPattern.kind === 175 /* ObjectBindingPattern */) { - writePunctuation(writer, 17 /* OpenBraceToken */); - buildDisplayForCommaSeparatedList(bindingPattern.elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 18 /* CloseBraceToken */); - } - else if (bindingPattern.kind === 176 /* ArrayBindingPattern */) { - writePunctuation(writer, 21 /* OpenBracketToken */); - var elements = bindingPattern.elements; - buildDisplayForCommaSeparatedList(elements, writer, function (e) { return buildBindingElementDisplay(e, writer, enclosingDeclaration, flags, symbolStack); }); - if (elements && elements.hasTrailingComma) { - writePunctuation(writer, 26 /* CommaToken */); - } - writePunctuation(writer, 22 /* CloseBracketToken */); - } - } - function buildBindingElementDisplay(bindingElement, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isOmittedExpression(bindingElement)) { - return; - } - ts.Debug.assert(bindingElement.kind === 177 /* BindingElement */); - if (bindingElement.propertyName) { - writer.writeProperty(ts.getTextOfNode(bindingElement.propertyName)); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - } - if (ts.isBindingPattern(bindingElement.name)) { - buildBindingPatternDisplay(bindingElement.name, writer, enclosingDeclaration, flags, symbolStack); - } - else { - if (bindingElement.dotDotDotToken) { - writePunctuation(writer, 24 /* DotDotDotToken */); - } - appendSymbolNameOnly(bindingElement.symbol, writer); - } - } - function buildDisplayForTypeParametersAndDelimiters(typeParameters, writer, enclosingDeclaration, flags, symbolStack) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - buildDisplayForCommaSeparatedList(typeParameters, writer, function (p) { return buildTypeParameterDisplay(p, writer, enclosingDeclaration, flags, symbolStack); }); - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForCommaSeparatedList(list, writer, action) { - for (var i = 0; i < list.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - action(list[i]); - } - } - function buildDisplayForTypeArgumentsAndDelimiters(typeParameters, mapper, writer, enclosingDeclaration) { - if (typeParameters && typeParameters.length) { - writePunctuation(writer, 27 /* LessThanToken */); - var flags = 512 /* InFirstTypeArgument */; - for (var i = 0; i < typeParameters.length; i++) { - if (i > 0) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - flags = 0 /* None */; - } - buildTypeDisplay(mapper(typeParameters[i]), writer, enclosingDeclaration, flags); - } - writePunctuation(writer, 29 /* GreaterThanToken */); - } - } - function buildDisplayForParametersAndDelimiters(thisParameter, parameters, writer, enclosingDeclaration, flags, symbolStack) { - writePunctuation(writer, 19 /* OpenParenToken */); - if (thisParameter) { - buildParameterDisplay(thisParameter, writer, enclosingDeclaration, flags, symbolStack); - } - for (var i = 0; i < parameters.length; i++) { - if (i > 0 || thisParameter) { - writePunctuation(writer, 26 /* CommaToken */); - writeSpace(writer); - } - buildParameterDisplay(parameters[i], writer, enclosingDeclaration, flags, symbolStack); - } - writePunctuation(writer, 20 /* CloseParenToken */); - } - function buildTypePredicateDisplay(predicate, writer, enclosingDeclaration, flags, symbolStack) { - if (ts.isIdentifierTypePredicate(predicate)) { - writer.writeParameter(predicate.parameterName); - } - else { - writeKeyword(writer, 99 /* ThisKeyword */); - } - writeSpace(writer); - writeKeyword(writer, 126 /* IsKeyword */); - writeSpace(writer); - buildTypeDisplay(predicate.type, writer, enclosingDeclaration, flags, symbolStack); - } - function buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack) { - var returnType = getReturnTypeOfSignature(signature); - if (flags & 4096 /* SuppressAnyReturnType */ && isTypeAny(returnType)) { - return; - } - if (flags & 16 /* WriteArrowStyleSignature */) { - writeSpace(writer); - writePunctuation(writer, 36 /* EqualsGreaterThanToken */); - } - else { - writePunctuation(writer, 56 /* ColonToken */); - } - writeSpace(writer); - var typePredicate = getTypePredicateOfSignature(signature); - if (typePredicate) { - buildTypePredicateDisplay(typePredicate, writer, enclosingDeclaration, flags, symbolStack); - } - else { - buildTypeDisplay(returnType, writer, enclosingDeclaration, flags, symbolStack); - } - } - function buildSignatureDisplay(signature, writer, enclosingDeclaration, flags, kind, symbolStack) { - if (kind === 1 /* Construct */) { - writeKeyword(writer, 94 /* NewKeyword */); - writeSpace(writer); - } - if (signature.target && (flags & 64 /* WriteTypeArgumentsOfSignature */)) { - // Instantiated signature, write type arguments instead - // This is achieved by passing in the mapper separately - buildDisplayForTypeArgumentsAndDelimiters(signature.target.typeParameters, signature.mapper, writer, enclosingDeclaration); - } - else { - buildDisplayForTypeParametersAndDelimiters(signature.typeParameters, writer, enclosingDeclaration, flags, symbolStack); - } - buildDisplayForParametersAndDelimiters(signature.thisParameter, signature.parameters, writer, enclosingDeclaration, flags, symbolStack); - buildReturnTypeDisplay(signature, writer, enclosingDeclaration, flags, symbolStack); - } - function buildIndexSignatureDisplay(info, writer, kind, enclosingDeclaration, globalFlags, symbolStack) { - if (info) { - if (info.isReadonly) { - writeKeyword(writer, 131 /* ReadonlyKeyword */); - writeSpace(writer); - } - writePunctuation(writer, 21 /* OpenBracketToken */); - writer.writeParameter(info.declaration ? ts.declarationNameToString(info.declaration.parameters[0].name) : "x"); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - switch (kind) { - case 1 /* Number */: - writeKeyword(writer, 133 /* NumberKeyword */); - break; - case 0 /* String */: - writeKeyword(writer, 136 /* StringKeyword */); - break; - } - writePunctuation(writer, 22 /* CloseBracketToken */); - writePunctuation(writer, 56 /* ColonToken */); - writeSpace(writer); - if (info.type) { - buildTypeDisplay(info.type, writer, enclosingDeclaration, globalFlags, symbolStack); - } - else { - writeKeyword(writer, 119 /* AnyKeyword */); - } - writePunctuation(writer, 25 /* SemicolonToken */); - writer.writeLine(); - } - } - return _displayBuilder || (_displayBuilder = { - buildSymbolDisplay: buildSymbolDisplay, - buildTypeDisplay: buildTypeDisplay, - buildTypeParameterDisplay: buildTypeParameterDisplay, - buildTypePredicateDisplay: buildTypePredicateDisplay, - buildParameterDisplay: buildParameterDisplay, - buildDisplayForParametersAndDelimiters: buildDisplayForParametersAndDelimiters, - buildDisplayForTypeParametersAndDelimiters: buildDisplayForTypeParametersAndDelimiters, - buildTypeParameterDisplayFromSymbol: buildTypeParameterDisplayFromSymbol, - buildSignatureDisplay: buildSignatureDisplay, - buildIndexSignatureDisplay: buildIndexSignatureDisplay, - buildReturnTypeDisplay: buildReturnTypeDisplay - }); - } function isDeclarationVisible(node) { if (node) { var links = getNodeLinks(node); @@ -28124,8 +27772,8 @@ var ts; var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName); if (resolutionCycleStartIndex >= 0) { // A cycle was found - var length_3 = resolutionTargets.length; - for (var i = resolutionCycleStartIndex; i < length_3; i++) { + var length_2 = resolutionTargets.length; + for (var i = resolutionCycleStartIndex; i < length_2; i++) { resolutionResults[i] = false; } return false; @@ -28159,6 +27807,10 @@ var ts; if (propertyName === 3 /* ResolvedReturnType */) { return target.resolvedReturnType; } + if (propertyName === 4 /* ResolvedBaseConstraint */) { + var bc = target.resolvedBaseConstraint; + return bc && bc !== circularConstraintType; + } ts.Debug.fail("Unhandled TypeSystemPropertyName " + propertyName); } // Pop an entry from the type resolution stack and return its associated result value. The result value will @@ -28283,7 +27935,8 @@ var ts; if (strictNullChecks && declaration.flags & 2097152 /* Ambient */ && ts.isParameterDeclaration(declaration)) { parentType = getNonNullableType(parentType); } - var declaredType = getTypeOfPropertyOfType(parentType, text); + var propType = getTypeOfPropertyOfType(parentType, text); + var declaredType = propType && getApparentTypeForLocation(propType, declaration.name); type = declaredType && getFlowTypeOfReference(declaration, declaredType) || isNumericLiteralName(text) && getIndexTypeOfType(parentType, 1 /* Number */) || getIndexTypeOfType(parentType, 0 /* String */); @@ -29077,7 +28730,7 @@ var ts; return type.resolvedBaseTypes = ts.emptyArray; } if (type === baseType || hasBaseType(baseType, type)) { - error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); return type.resolvedBaseTypes = ts.emptyArray; } if (type.resolvedBaseTypes === ts.resolvingEmptyArray) { @@ -29125,7 +28778,7 @@ var ts; } } else { - error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */)); + error(declaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */)); } } else { @@ -29650,18 +29303,19 @@ var ts; } return symbol; } - function getTypeWithThisArgument(type, thisArgument) { + function getTypeWithThisArgument(type, thisArgument, needApparentType) { if (ts.getObjectFlags(type) & 4 /* Reference */) { var target = type.target; var typeArguments = type.typeArguments; if (ts.length(target.typeParameters) === ts.length(typeArguments)) { - return createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType])); + return needApparentType ? getApparentType(ref) : ref; } } else if (type.flags & 262144 /* Intersection */) { - return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument); })); + return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); })); } - return type; + return needApparentType ? getApparentType(type) : type; } function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) { var mapper; @@ -30207,12 +29861,17 @@ var ts; return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined; } function getConstraintOfIndexedAccess(type) { - var transformed = getTransformedIndexedAccessType(type); + var transformed = getSimplifiedIndexedAccessType(type); if (transformed) { return transformed; } var baseObjectType = getBaseConstraintOfType(type.objectType); var baseIndexType = getBaseConstraintOfType(type.indexType); + if (baseIndexType === stringType && !getIndexInfoOfType(baseObjectType || type.objectType, 0 /* String */)) { + // getIndexedAccessType returns `any` for X[string] where X doesn't have an index signature. + // to avoid this, return `undefined`. + return undefined; + } return baseObjectType || baseIndexType ? getIndexedAccessType(baseObjectType || type.objectType, baseIndexType || type.indexType) : undefined; } function getBaseConstraintOfType(type) { @@ -30236,29 +29895,30 @@ var ts; * circularly references the type variable. */ function getResolvedBaseConstraint(type) { - var typeStack; var circular; if (!type.resolvedBaseConstraint) { - typeStack = []; var constraint = getBaseConstraint(type); type.resolvedBaseConstraint = circular ? circularConstraintType : getTypeWithThisArgument(constraint || noConstraintType, type); } return type.resolvedBaseConstraint; function getBaseConstraint(t) { - if (ts.contains(typeStack, t)) { + if (!pushTypeResolution(t, 4 /* ResolvedBaseConstraint */)) { circular = true; return undefined; } - typeStack.push(t); var result = computeBaseConstraint(t); - typeStack.pop(); + if (!popTypeResolution()) { + circular = true; + return undefined; + } return result; } function computeBaseConstraint(t) { if (t.flags & 32768 /* TypeParameter */) { var constraint = getConstraintFromTypeParameter(t); - return t.isThisType ? constraint : - constraint ? getBaseConstraint(constraint) : undefined; + return t.isThisType || !constraint ? + constraint : + getBaseConstraint(constraint); } if (t.flags & 393216 /* UnionOrIntersection */) { var types = t.types; @@ -30278,7 +29938,7 @@ var ts; return stringType; } if (t.flags & 1048576 /* IndexedAccess */) { - var transformed = getTransformedIndexedAccessType(t); + var transformed = getSimplifiedIndexedAccessType(t); if (transformed) { return getBaseConstraint(transformed); } @@ -30294,7 +29954,7 @@ var ts; } } function getApparentTypeOfIntersectionType(type) { - return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type)); + return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true)); } function getResolvedTypeParameterDefault(typeParameter) { if (!typeParameter.default) { @@ -30712,7 +30372,7 @@ var ts; // b) It references `arguments` somewhere var lastParam = ts.lastOrUndefined(declaration.parameters); var lastParamTags = lastParam && ts.getJSDocParameterTags(lastParam); - var lastParamVariadicType = lastParamTags && ts.firstDefined(lastParamTags, function (p) { + var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) { return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined; }); if (!lastParamVariadicType && !containsArgumentsReference(declaration)) { @@ -31006,12 +30666,12 @@ var ts; function getTypeListId(types) { var result = ""; if (types) { - var length_4 = types.length; + var length_3 = types.length; var i = 0; - while (i < length_4) { + while (i < length_3) { var startId = types[i].id; var count = 1; - while (i + count < length_4 && types[i + count].id === startId + count) { + while (i + count < length_3 && types[i + count].id === startId + count) { count++; } if (result.length) { @@ -31083,7 +30743,7 @@ var ts; : missingAugmentsTag ? ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag : ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments; - var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* WriteArrayAsGenericType */); + var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */); error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length); if (!isJs) { // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments) @@ -31629,8 +31289,8 @@ var ts; function getUnionTypePredicate(signatures) { var first; var types = []; - for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { - var sig = signatures_3[_i]; + for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { + var sig = signatures_2[_i]; var pred = getTypePredicateOfSignature(sig); if (!pred) { continue; @@ -31912,42 +31572,64 @@ var ts; } return false; } + function isMappedTypeToNever(type) { + return ts.getObjectFlags(type) & 32 /* Mapped */ && getTemplateTypeFromMappedType(type) === neverType; + } // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return // undefined if no transformation is possible. - function getTransformedIndexedAccessType(type) { + function getSimplifiedIndexedAccessType(type) { var objectType = type.objectType; - // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or - // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a - // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed - // access types with default property values as expressed by D. - if (objectType.flags & 262144 /* Intersection */ && isGenericObjectType(objectType) && ts.some(objectType.types, isStringIndexOnlyType)) { - var regularTypes = []; - var stringIndexTypes = []; - for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { - var t = _a[_i]; - if (isStringIndexOnlyType(t)) { - stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); - } - else { - regularTypes.push(t); + 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 + // more object types with only a string index signature, e.g. '(U & V & { [x: string]: D })[K]', return a + // transformed type of the form '(U & V)[K] | D'. This allows us to properly reason about higher order indexed + // access types with default property values as expressed by D. + if (ts.some(objectType.types, isStringIndexOnlyType)) { + var regularTypes = []; + var stringIndexTypes = []; + for (var _i = 0, _a = objectType.types; _i < _a.length; _i++) { + var t = _a[_i]; + if (isStringIndexOnlyType(t)) { + stringIndexTypes.push(getIndexTypeOfType(t, 0 /* String */)); + } + else { + regularTypes.push(t); + } } + return getUnionType([ + getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), + getIntersectionType(stringIndexTypes) + ]); + } + // Given an indexed access type T[K], if T is an intersection containing one or more generic types and one or + // more mapped types with a template type `never`, '(U & V & { [P in T]: never })[K]', return a + // transformed type that removes the never-mapped type: '(U & V)[K]'. This mirrors what would happen + // 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 getIndexedAccessType(getIntersectionType(nonNeverTypes), type.indexType); } - return getUnionType([ - getIndexedAccessType(getIntersectionType(regularTypes), type.indexType), - getIntersectionType(stringIndexTypes) - ]); } // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper // that substitutes the index type for P. For example, for an index access { [P in K]: Box }[X], we // construct the type Box. if (isGenericMappedType(objectType)) { - var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); - var objectTypeMapper = objectType.mapper; - var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; - return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + return substituteIndexedMappedType(objectType, type); + } + if (objectType.flags & 32768 /* TypeParameter */) { + var constraint = getConstraintFromTypeParameter(objectType); + if (constraint && isGenericMappedType(constraint)) { + return substituteIndexedMappedType(constraint, type); + } } return undefined; } + function substituteIndexedMappedType(objectType, type) { + var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [type.indexType]); + var objectTypeMapper = objectType.mapper; + var templateMapper = objectTypeMapper ? combineTypeMappers(objectTypeMapper, mapper) : mapper; + return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper); + } function getIndexedAccessType(objectType, indexType, accessNode) { // If the index type is generic, or if the object type is generic and doesn't originate in an expression, // we are performing a higher-order index access where we cannot meaningfully access the properties of the @@ -32876,7 +32558,7 @@ var ts; var targetProperty = getPropertyOfType(targetEnumType, property.escapedName); if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) { if (errorReporter) { - errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */)); + errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */)); } enumRelation.set(id, false); return false; @@ -33018,8 +32700,8 @@ var ts; var sourceType = typeToString(source); var targetType = typeToString(target); if (sourceType === targetType) { - sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); - targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 256 /* UseFullyQualifiedType */); + sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); + targetType = typeToString(target, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */); } if (!message) { if (relation === comparableRelation) { @@ -33500,7 +33182,7 @@ var ts; } else if (target.flags & 1048576 /* IndexedAccess */) { // A type S is related to a type T[K] if S is related to A[K], where K is string-like and - // A is the apparent type of S. + // A is the constraint of T. var constraint = getConstraintOfIndexedAccess(target); if (constraint) { if (result = isRelatedTo(source, constraint, reportErrors)) { @@ -33535,7 +33217,7 @@ var ts; } else if (source.flags & 1048576 /* IndexedAccess */) { // A type S[K] is related to a type T if A[K] is related to T, where K is string-like and - // A is the apparent type of S. + // A is the constraint of S. var constraint = getConstraintOfIndexedAccess(source); if (constraint) { if (result = isRelatedTo(constraint, target, reportErrors)) { @@ -33543,10 +33225,11 @@ var ts; return result; } } - else if (target.flags & 1048576 /* IndexedAccess */ && source.indexType === target.indexType) { - // if we have indexed access types with identical index types, see if relationship holds for - // the two object types. + else if (target.flags & 1048576 /* IndexedAccess */) { if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) { + result &= isRelatedTo(source.indexType, target.indexType, reportErrors); + } + if (result) { errorInfo = saveErrorInfo; return result; } @@ -34703,6 +34386,7 @@ var ts; return { typeParameter: typeParameter, candidates: undefined, + contraCandidates: undefined, inferredType: undefined, priority: undefined, topLevel: true, @@ -34713,6 +34397,7 @@ var ts; return { typeParameter: inference.typeParameter, candidates: inference.candidates && inference.candidates.slice(), + contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(), inferredType: inference.inferredType, priority: inference.priority, topLevel: inference.topLevel, @@ -34739,7 +34424,7 @@ var ts; function isTypeParameterAtTopLevel(type, typeParameter) { return type === typeParameter || type.flags & 393216 /* UnionOrIntersection */ && ts.forEach(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }); } - /** Create an object with properties named in the string literal type. Every property has type `{}` */ + /** Create an object with properties named in the string literal type. Every property has type `any` */ function createEmptyObjectTypeFromStringLiteral(type) { var members = ts.createSymbolTable(); forEachType(type, function (t) { @@ -34748,7 +34433,7 @@ var ts; } var name = ts.escapeLeadingUnderscores(t.value); var literalProp = createSymbol(4 /* Property */, name); - literalProp.type = emptyObjectType; + literalProp.type = anyType; if (t.symbol) { literalProp.declarations = t.symbol.declarations; literalProp.valueDeclaration = t.symbol.valueDeclaration; @@ -34800,7 +34485,9 @@ var ts; var templateType = getTemplateTypeFromMappedType(target); var inference = createInferenceInfo(typeParameter); inferTypes([inference], sourceType, templateType); - return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : emptyObjectType; + return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) : + inference.contraCandidates ? getCommonSubtype(inference.contraCandidates) : + emptyObjectType; } function getUnmatchedProperty(source, target, requireOptionalProperties) { var properties = target.flags & 262144 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(target) : getPropertiesOfObjectType(target); @@ -34819,6 +34506,7 @@ var ts; if (priority === void 0) { priority = 0; } var symbolStack; var visited; + var contravariant = false; inferFromTypes(originalSource, originalTarget); function inferFromTypes(source, target) { if (!couldContainTypeVariables(target)) { @@ -34887,18 +34575,20 @@ var ts; var inference = getInferenceInfoForType(target); if (inference) { if (!inference.isFixed) { - // We give lowest priority to inferences of implicitNeverType (which is used as the - // element type for empty array literals). Thus, inferences from empty array literals - // only matter when no other inferences are made. - var p = priority | (source === implicitNeverType ? 16 /* NeverType */ : 0); - if (!inference.candidates || p < inference.priority) { - inference.candidates = [source]; - inference.priority = p; + if (inference.priority === undefined || priority < inference.priority) { + inference.candidates = undefined; + inference.contraCandidates = undefined; + inference.priority = priority; } - else if (p === inference.priority) { - inference.candidates.push(source); + if (priority === inference.priority) { + if (contravariant) { + inference.contraCandidates = ts.append(inference.contraCandidates, source); + } + else { + inference.candidates = ts.append(inference.candidates, source); + } } - if (!(p & 8 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { + if (!(priority & 4 /* ReturnType */) && target.flags & 32768 /* TypeParameter */ && !isTypeParameterAtTopLevel(originalTarget, target)) { inference.topLevel = false; } } @@ -34921,15 +34611,15 @@ var ts; } } else if (source.flags & 524288 /* Index */ && target.flags & 524288 /* Index */) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source.type, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if ((isLiteralType(source) || source.flags & 2 /* String */) && target.flags & 524288 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(empty, target.type); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else if (source.flags & 1048576 /* IndexedAccess */ && target.flags & 1048576 /* IndexedAccess */) { inferFromTypes(source.objectType, target.objectType); @@ -34955,7 +34645,7 @@ var ts; // types in contra-variant positions (such as callback parameters). if (typeVariableCount === 1) { var savePriority = priority; - priority |= 2 /* NakedTypeVariable */; + priority |= 1 /* NakedTypeVariable */; inferFromTypes(source, typeVariable); priority = savePriority; } @@ -34999,9 +34689,9 @@ var ts; } function inferFromContravariantTypes(source, target) { if (strictFunctionTypes) { - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; inferFromTypes(source, target); - priority ^= 1 /* Contravariant */; + contravariant = !contravariant; } else { inferFromTypes(source, target); @@ -35037,7 +34727,7 @@ var ts; var inferredType = inferTypeForHomomorphicMappedType(source, target); if (inferredType) { var savePriority = priority; - priority |= 4 /* MappedType */; + priority |= 2 /* MappedType */; inferFromTypes(inferredType, inference.typeParameter); priority = savePriority; } @@ -35171,10 +34861,19 @@ var ts; // If all inferences were made from contravariant positions, infer a common subtype. Otherwise, if // union types were requested or if all inferences were made from the return type position, infer a // union type. Otherwise, infer a common supertype. - var unwidenedType = inference.priority & 1 /* Contravariant */ ? getCommonSubtype(baseCandidates) : - context.flags & 1 /* InferUnionTypes */ || inference.priority & 8 /* ReturnType */ ? getUnionType(baseCandidates, 2 /* Subtype */) : - getCommonSupertype(baseCandidates); + var unwidenedType = context.flags & 1 /* InferUnionTypes */ || inference.priority & 4 /* ReturnType */ ? + getUnionType(baseCandidates, 2 /* Subtype */) : + getCommonSupertype(baseCandidates); inferredType = getWidenedType(unwidenedType); + // If we have inferred 'never' but have contravariant candidates. To get a more specific type we + // infer from the contravariant candidates instead. + if (inferredType.flags & 16384 /* Never */ && inference.contraCandidates) { + inferredType = getCommonSubtype(inference.contraCandidates); + } + } + else if (inference.contraCandidates) { + // We only have contravariant inferences, infer the best common subtype of those + inferredType = getCommonSubtype(inference.contraCandidates); } else if (context.flags & 2 /* NoDefault */) { // We use silentNeverType as the wildcard that signals no inferences. @@ -35486,16 +35185,6 @@ var ts; return 8388607 /* All */; } function getTypeWithFacts(type, include) { - if (type.flags & 1048576 /* IndexedAccess */) { - // TODO (weswig): This is a substitute for a lazy negated type to remove the types indicated by the TypeFacts from the (potential) union the IndexedAccess refers to - // - See discussion in https://github.com/Microsoft/TypeScript/pull/19275 for details, and test `strictNullNotNullIndexTypeShouldWork` for current behavior - var baseConstraint = getBaseConstraintOfType(type) || emptyObjectType; - var result = filterType(baseConstraint, function (t) { return (getTypeFacts(t) & include) !== 0; }); - if (result !== baseConstraint) { - return result; - } - return type; - } return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; }); } function getTypeWithDefault(type, defaultExpression) { @@ -36533,17 +36222,18 @@ var ts; var parent = node.parent; return parent.kind === 180 /* PropertyAccessExpression */ || parent.kind === 182 /* CallExpression */ && parent.expression === node || - parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node; + parent.kind === 181 /* ElementAccessExpression */ && parent.expression === node || + parent.kind === 204 /* NonNullExpression */ || + parent.kind === 177 /* BindingElement */ && parent.name === node && !!parent.initializer; } function typeHasNullableConstraint(type) { return type.flags & 1081344 /* TypeVariable */ && maybeTypeOfKind(getBaseConstraintOfType(type) || emptyObjectType, 12288 /* Nullable */); } - function getDeclaredOrApparentType(symbol, node) { + function getApparentTypeForLocation(type, node) { // When a node is the left hand expression of a property access, element access, or call expression, // and the type of the node includes type variables with constraints that are nullable, we fetch the // apparent type of the node *before* performing control flow analysis such that narrowings apply to // the constraint type. - var type = getTypeOfSymbol(symbol); if (isApparentTypePosition(node) && forEachType(type, typeHasNullableConstraint)) { return mapType(getWidenedType(type), getApparentType); } @@ -36622,7 +36312,7 @@ var ts; checkCollisionWithCapturedThisVariable(node, node); checkCollisionWithCapturedNewTargetVariable(node, node); checkNestedBlockScopedBinding(node, symbol); - var type = getDeclaredOrApparentType(localOrExportSymbol, node); + var type = getApparentTypeForLocation(getTypeOfSymbol(localOrExportSymbol), node); var assignmentKind = ts.getAssignmentTargetKind(node); if (assignmentKind) { if (!(localOrExportSymbol.flags & 3 /* Variable */)) { @@ -36872,6 +36562,15 @@ var ts; if (needToCaptureLexicalThis) { captureLexicalThis(node, container); } + var type = tryGetThisTypeAt(node, container); + if (!type && noImplicitThis) { + // With noImplicitThis, functions may not reference 'this' if it has type 'any' + error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); + } + return type || anyType; + } + function tryGetThisTypeAt(node, container) { + if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); } if (ts.isFunctionLike(container) && (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) { // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated. @@ -36906,11 +36605,6 @@ var ts; return type; } } - if (noImplicitThis) { - // With noImplicitThis, functions may not reference 'this' if it has type 'any' - error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation); - } - return anyType; } function getTypeForThisExpressionFromJSDoc(node) { var jsdocType = ts.getJSDocType(node); @@ -37598,7 +37292,7 @@ var ts; // If the given type is an object or union type with a single signature, and if that signature has at // least as many parameters as the given function, return the signature. Otherwise return undefined. function getContextualCallSignature(type, node) { - var signatures = getSignaturesOfStructuredType(type, 0 /* Call */); + var signatures = getSignaturesOfType(type, 0 /* Call */); if (signatures.length === 1) { var signature = signatures[0]; if (!isAritySmaller(signature, node)) { @@ -38248,8 +37942,8 @@ var ts; if (sourceAttributesType) { // Instantiate in context of source type var instantiatedSignatures = []; - for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) { - var signature = signatures_4[_i]; + for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) { + var signature = signatures_3[_i]; if (signature.typeParameters) { var isJavascript = ts.isInJavaScriptFile(node); var inferenceContext = createInferenceContext(signature, /*flags*/ isJavascript ? 4 /* AnyDefault */ : 0); @@ -38943,7 +38637,7 @@ var ts; return unknownType; } } - propType = getDeclaredOrApparentType(prop, node); + propType = getApparentTypeForLocation(getTypeOfSymbol(prop), node); } // Only compute control flow type if this is a property access expression that isn't an // assignment target, and the referenced property was declared as a variable, property, @@ -39194,7 +38888,7 @@ var ts; } function isValidMethodAccess(method, type) { var propType = getTypeOfFuncClassEnumModule(method); - var signatures = getSignaturesOfType(propType, 0 /* Call */); + var signatures = getSignaturesOfType(getNonNullableType(propType), 0 /* Call */); ts.Debug.assert(signatures.length !== 0); return signatures.some(function (sig) { var thisType = getThisTypeOfSignature(sig); @@ -39369,8 +39063,8 @@ var ts; var specializedIndex = -1; var spliceIndex; ts.Debug.assert(!result.length); - for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { - var signature = signatures_5[_i]; + 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 = signature.declaration && signature.declaration.parent; if (!lastSymbol || symbol === lastSymbol) { @@ -39505,7 +39199,7 @@ var ts; inferTypes(context.inferences, instantiateType(source, contextualMapper || identityMapper), target); }); if (!contextualMapper) { - inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 8 /* ReturnType */); + inferTypes(context.inferences, getReturnTypeOfSignature(contextualSignature), getReturnTypeOfSignature(signature), 4 /* ReturnType */); } return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJavaScriptFile(contextualSignature.declaration)); } @@ -39550,7 +39244,7 @@ var ts; instantiatedType; var inferenceTargetType = getReturnTypeOfSignature(signature); // Inferences made from return types have lower priority than all other inferences. - inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 8 /* ReturnType */); + inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 4 /* ReturnType */); } } var thisType = getThisTypeOfSignature(signature); @@ -40099,8 +39793,8 @@ var ts; else if (typeArguments && ts.every(signatures, function (sig) { return ts.length(sig.typeParameters) !== typeArguments.length; })) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) { - var sig = signatures_6[_i]; + for (var _i = 0, signatures_5 = signatures; _i < signatures_5.length; _i++) { + var sig = signatures_5[_i]; min = Math.min(min, getMinTypeArgumentCount(sig.typeParameters)); max = Math.max(max, ts.length(sig.typeParameters)); } @@ -40110,8 +39804,8 @@ var ts; else if (args) { var min = Number.POSITIVE_INFINITY; var max = Number.NEGATIVE_INFINITY; - for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { - var sig = signatures_7[_a]; + for (var _a = 0, signatures_6 = signatures; _a < signatures_6.length; _a++) { + var sig = signatures_6[_a]; min = Math.min(min, sig.minArgumentCount); max = Math.max(max, sig.parameters.length); } @@ -41480,6 +41174,9 @@ var ts; } function checkObjectLiteralAssignment(node, sourceType) { var properties = node.properties; + if (strictNullChecks && properties.length === 0) { + return checkNonNullType(sourceType, node); + } for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) { var p = properties_7[_i]; checkObjectLiteralDestructuringPropertyAssignment(sourceType, p, properties); @@ -43093,8 +42790,8 @@ var ts; if (bodyDeclaration) { var signatures = getSignaturesOfSymbol(symbol); var bodySignature = getSignatureFromDeclaration(bodyDeclaration); - for (var _a = 0, signatures_8 = signatures; _a < signatures_8.length; _a++) { - var signature = signatures_8[_a]; + for (var _a = 0, signatures_7 = signatures; _a < signatures_7.length; _a++) { + var signature = signatures_7[_a]; if (!isImplementationCompatibleWithOverload(bodySignature, signature)) { error(signature.declaration, ts.Diagnostics.Overload_signature_is_not_compatible_with_function_implementation); break; @@ -44236,7 +43933,13 @@ var ts; if (ts.isBindingPattern(node.name)) { // Don't validate for-in initializer as it is already an error if (node.initializer && node.parent.parent.kind !== 216 /* ForInStatement */) { - checkTypeAssignableTo(checkExpressionCached(node.initializer), getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + var initializerType = checkExpressionCached(node.initializer); + if (strictNullChecks && node.name.elements.length === 0) { + checkNonNullType(initializerType, node); + } + else { + checkTypeAssignableTo(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, /*headMessage*/ undefined); + } checkParameterInitializer(node); } return; @@ -44992,7 +44695,8 @@ var ts; error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType)); } function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) { - if (!indexType) { + // ESSymbol properties apply to neither string nor numeric indexers. + if (!indexType || ts.isKnownSymbol(prop)) { return; } var propDeclaration = prop.valueDeclaration; @@ -47344,20 +47048,20 @@ var ts; : unknownType; if (type.flags & 1024 /* UniqueESSymbol */ && type.symbol === symbol) { - flags |= 131072 /* AllowUniqueESSymbolType */; + flags |= 1048576 /* AllowUniqueESSymbolType */; } - if (flags & 8192 /* AddUndefined */) { + if (flags & 131072 /* AddUndefined */) { type = getOptionalType(type); } - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeReturnTypeOfSignatureDeclaration(signatureDeclaration, enclosingDeclaration, flags, writer) { var signature = getSignatureFromDeclaration(signatureDeclaration); - getSymbolDisplayBuilder().buildTypeDisplay(getReturnTypeOfSignature(signature), writer, enclosingDeclaration, flags); + typeToString(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function writeTypeOfExpression(expr, enclosingDeclaration, flags, writer) { var type = getWidenedType(getRegularTypeOfExpression(expr)); - getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typeToString(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); } function hasGlobalName(name) { return globals.has(ts.escapeLeadingUnderscores(name)); @@ -48507,12 +48211,15 @@ var ts; function checkGrammarBindingElement(node) { if (node.dotDotDotToken) { var elements = node.parent.elements; - if (node !== ts.lastOrUndefined(elements)) { + if (node !== ts.last(elements)) { return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern); } if (node.name.kind === 176 /* ArrayBindingPattern */ || node.name.kind === 175 /* ObjectBindingPattern */) { return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern); } + if (node.propertyName) { + return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name); + } if (node.initializer) { // Error on equals token which immediately precedes the initializer return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer); @@ -48971,7 +48678,7 @@ var ts; var node = createSynthesizedNode(71 /* Identifier */); node.escapedText = ts.escapeLeadingUnderscores(text); node.originalKeywordKind = text ? ts.stringToToken(text) : 0 /* Unknown */; - node.autoGenerateKind = 0 /* None */; + node.autoGenerateFlags = 0 /* None */; node.autoGenerateId = 0; if (typeArguments) { node.typeArguments = createNodeArray(typeArguments); @@ -48986,22 +48693,24 @@ var ts; } ts.updateIdentifier = updateIdentifier; var nextAutoGenerateId = 0; - /** Create a unique temporary variable. */ - function createTempVariable(recordTempVariable) { + function createTempVariable(recordTempVariable, reservedInNestedScopes) { var name = createIdentifier(""); - name.autoGenerateKind = 1 /* Auto */; + name.autoGenerateFlags = 1 /* Auto */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; if (recordTempVariable) { recordTempVariable(name); } + if (reservedInNestedScopes) { + name.autoGenerateFlags |= 16 /* ReservedInNestedScopes */; + } return name; } ts.createTempVariable = createTempVariable; /** Create a unique temporary variable for use in a loop. */ function createLoopVariable() { var name = createIdentifier(""); - name.autoGenerateKind = 2 /* Loop */; + name.autoGenerateFlags = 2 /* Loop */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -49010,7 +48719,7 @@ var ts; /** Create a unique name based on the supplied text. */ function createUniqueName(text) { var name = createIdentifier(text); - name.autoGenerateKind = 3 /* Unique */; + name.autoGenerateFlags = 3 /* Unique */; name.autoGenerateId = nextAutoGenerateId; nextAutoGenerateId++; return name; @@ -49018,10 +48727,12 @@ var ts; ts.createUniqueName = createUniqueName; function getGeneratedNameForNode(node, shouldSkipNameGenerationScope) { var name = createIdentifier(""); - name.autoGenerateKind = 4 /* Node */; + name.autoGenerateFlags = 4 /* Node */; name.autoGenerateId = nextAutoGenerateId; name.original = node; - name.skipNameGenerationScope = !!shouldSkipNameGenerationScope; + if (shouldSkipNameGenerationScope) { + name.autoGenerateFlags |= 8 /* SkipNameGenerationScope */; + } nextAutoGenerateId++; return name; } @@ -49319,11 +49030,12 @@ var ts; } ts.updateIndexSignature = updateIndexSignature; /* @internal */ - function createSignatureDeclaration(kind, typeParameters, parameters, type) { + function createSignatureDeclaration(kind, typeParameters, parameters, type, typeArguments) { var node = createSynthesizedNode(kind); node.typeParameters = asNodeArray(typeParameters); node.parameters = asNodeArray(parameters); node.type = type; + node.typeArguments = asNodeArray(typeArguments); return node; } ts.createSignatureDeclaration = createSignatureDeclaration; @@ -52292,7 +52004,9 @@ var ts; // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions // so in case when comma expression is introduced as a part of previous transformations // if should be wrapped in parens since comma operator has the lowest precedence - return e.kind === 195 /* BinaryExpression */ && e.operatorToken.kind === 26 /* CommaToken */ + var emittedExpression = ts.skipPartiallyEmittedExpressions(e); + return emittedExpression.kind === 195 /* BinaryExpression */ && emittedExpression.operatorToken.kind === 26 /* CommaToken */ || + emittedExpression.kind === 293 /* CommaListExpression */ ? ts.createParen(e) : e; } @@ -52942,6 +52656,7 @@ var ts; /// var ts; (function (ts) { + var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration); function visitNode(node, visitor, test, lift) { if (node === undefined || visitor === undefined) { return node; @@ -53076,7 +52791,7 @@ var ts; switch (kind) { // Names case 71 /* Identifier */: - return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, ts.isTypeNode)); + return ts.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration)); case 144 /* QualifiedName */: return ts.updateQualifiedName(node, visitNode(node.left, visitor, ts.isEntityName), visitNode(node.right, visitor, ts.isIdentifier)); case 145 /* ComputedPropertyName */: @@ -54147,7 +53862,12 @@ var ts; }; if (value) { value = ts.visitNode(value, visitor, ts.isExpression); - if (needsValue) { + if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location); + } + else if (needsValue) { // If the right-hand value of the destructuring assignment needs to be preserved (as // is the case when the destructuring assignment is part of a larger expression), // then we need to cache the right-hand value. @@ -54191,6 +53911,26 @@ var ts; } } ts.flattenDestructuringAssignment = flattenDestructuringAssignment; + function bindingOrAssignmentElementAssignsToName(element, escapedName) { + var target = ts.getTargetOfBindingOrAssignmentElement(element); + if (ts.isBindingOrAssignmentPattern(target)) { + return bindingOrAssignmentPatternAssignsToName(target, escapedName); + } + else if (ts.isIdentifier(target)) { + return target.escapedText === escapedName; + } + return false; + } + function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) { + var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern); + for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { + var element = elements_3[_i]; + if (bindingOrAssignmentElementAssignsToName(element, escapedName)) { + return true; + } + } + return false; + } /** * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations. * @@ -54218,6 +53958,15 @@ var ts; createArrayBindingOrAssignmentElement: makeBindingElement, visitor: visitor }; + if (ts.isVariableDeclaration(node)) { + var initializer = ts.getInitializerOfBindingOrAssignmentElement(node); + if (initializer && ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText)) { + // If the right-hand value of the assignment is also an assignment target then + // we need to cache the right-hand value. + initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer); + node = ts.updateVariableDeclaration(node, node.name, node.type, initializer); + } + } flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer); if (pendingExpressions) { var temp = ts.createTempVariable(/*recordTempVariable*/ undefined); @@ -55303,11 +55052,14 @@ var ts; ts.setTextRange(classExpression, node); if (ts.some(staticProperties) || ts.some(pendingExpressions)) { var expressions = []; - var temp = ts.createTempVariable(hoistVariableDeclaration); - if (resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */) { + var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 8388608 /* ClassWithConstructorReference */; + var temp = ts.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference); + if (isClassWithConstructorReference) { // record an alias as the class name is not in scope for statics. enableSubstitutionForClassAliases(); - classAliases[ts.getOriginalNodeId(node)] = ts.getSynthesizedClone(temp); + var alias = ts.getSynthesizedClone(temp); + alias.autoGenerateFlags &= ~16 /* ReservedInNestedScopes */; + classAliases[ts.getOriginalNodeId(node)] = alias; } // To preserve the behavior of the old emitter, we explicitly indent // the body of a class with static initializers. @@ -57476,7 +57228,7 @@ var ts; ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper"; })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {})); function transformES2017(context) { - var startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment; + var resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration; var resolver = context.getEmitResolver(); var compilerOptions = context.getCompilerOptions(); var languageVersion = ts.getEmitScriptTarget(compilerOptions); @@ -57490,6 +57242,7 @@ var ts; * just-in-time substitution for `super` expressions inside of async methods. */ var enclosingSuperContainerFlags = 0; + var enclosingFunctionParameterNames; // Save the previous transformation hooks. var previousOnEmitNode = context.onEmitNode; var previousOnSubstituteNode = context.onSubstituteNode; @@ -57527,6 +57280,83 @@ var ts; return ts.visitEachChild(node, visitor, context); } } + function asyncBodyVisitor(node) { + if (ts.isNodeWithPossibleHoistedDeclaration(node)) { + switch (node.kind) { + case 209 /* VariableStatement */: + return visitVariableStatementInAsyncBody(node); + case 215 /* ForStatement */: + return visitForStatementInAsyncBody(node); + case 216 /* ForInStatement */: + return visitForInStatementInAsyncBody(node); + case 217 /* ForOfStatement */: + return visitForOfStatementInAsyncBody(node); + case 264 /* CatchClause */: + return visitCatchClauseInAsyncBody(node); + case 208 /* Block */: + case 222 /* SwitchStatement */: + case 236 /* CaseBlock */: + case 261 /* CaseClause */: + case 262 /* DefaultClause */: + case 225 /* TryStatement */: + case 213 /* DoStatement */: + case 214 /* WhileStatement */: + case 212 /* IfStatement */: + case 221 /* WithStatement */: + case 223 /* LabeledStatement */: + return ts.visitEachChild(node, asyncBodyVisitor, context); + default: + return ts.Debug.assertNever(node, "Unhandled node."); + } + } + return visitor(node); + } + function visitCatchClauseInAsyncBody(node) { + var catchClauseNames = ts.createUnderscoreEscapedMap(); + recordDeclarationName(node.variableDeclaration, catchClauseNames); + // names declared in a catch variable are block scoped + var catchClauseUnshadowedNames; + catchClauseNames.forEach(function (_, escapedName) { + if (enclosingFunctionParameterNames.has(escapedName)) { + if (!catchClauseUnshadowedNames) { + catchClauseUnshadowedNames = ts.cloneMap(enclosingFunctionParameterNames); + } + catchClauseUnshadowedNames.delete(escapedName); + } + }); + if (catchClauseUnshadowedNames) { + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = catchClauseUnshadowedNames; + var result = ts.visitEachChild(node, asyncBodyVisitor, context); + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; + } + else { + return ts.visitEachChild(node, asyncBodyVisitor, context); + } + } + function visitVariableStatementInAsyncBody(node) { + if (isVariableDeclarationListWithCollidingName(node.declarationList)) { + var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false); + return expression ? ts.createStatement(expression) : undefined; + } + return ts.visitEachChild(node, visitor, context); + } + function visitForInStatementInAsyncBody(node) { + return ts.updateForIn(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForOfStatementInAsyncBody(node) { + return ts.updateForOf(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } + function visitForStatementInAsyncBody(node) { + return ts.updateFor(node, isVariableDeclarationListWithCollidingName(node.initializer) + ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ false) + : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, ts.liftToBlock)); + } /** * Visits an AwaitExpression node. * @@ -57601,6 +57431,73 @@ var ts; ? transformAsyncFunctionBody(node) : ts.visitFunctionBody(node.body, visitor, context)); } + function recordDeclarationName(_a, names) { + var name = _a.name; + if (ts.isIdentifier(name)) { + names.set(name.escapedText, true); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + recordDeclarationName(element, names); + } + } + } + } + function isVariableDeclarationListWithCollidingName(node) { + return node + && ts.isVariableDeclarationList(node) + && !(node.flags & 3 /* BlockScoped */) + && ts.forEach(node.declarations, collidesWithParameterName); + } + function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) { + hoistVariableDeclarationList(node); + var variables = ts.getInitializedVariables(node); + if (variables.length === 0) { + if (hasReceiver) { + return ts.visitNode(ts.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression); + } + return undefined; + } + return ts.inlineExpressions(ts.map(variables, transformInitializedVariable)); + } + function hoistVariableDeclarationList(node) { + ts.forEach(node.declarations, hoistVariable); + } + function hoistVariable(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + hoistVariableDeclaration(name); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element)) { + hoistVariable(element); + } + } + } + } + function transformInitializedVariable(node) { + var converted = ts.setSourceMapRange(ts.createAssignment(ts.convertToAssignmentElementTarget(node.name), node.initializer), node); + return ts.visitNode(converted, visitor, ts.isExpression); + } + function collidesWithParameterName(_a) { + var name = _a.name; + if (ts.isIdentifier(name)) { + return enclosingFunctionParameterNames.has(name.escapedText); + } + else { + for (var _i = 0, _b = name.elements; _i < _b.length; _i++) { + var element = _b[_i]; + if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) { + return true; + } + } + } + return false; + } function transformAsyncFunctionBody(node) { resumeLexicalEnvironment(); var original = ts.getOriginalNode(node, ts.isFunctionLike); @@ -57613,10 +57510,17 @@ var ts; // `this` and `arguments` objects to `__awaiter`. The generator function // passed to `__awaiter` is executed inside of the callback to the // promise constructor. + var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames; + enclosingFunctionParameterNames = ts.createUnderscoreEscapedMap(); + for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) { + var parameter = _a[_i]; + recordDeclarationName(parameter, enclosingFunctionParameterNames); + } + var result; if (!isArrowFunction) { var statements = []; var statementOffset = ts.addPrologue(statements, node.body.statements, /*ensureUseStrict*/ false, visitor); - statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body, statementOffset)))); + statements.push(ts.createReturn(createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset)))); ts.addRange(statements, endLexicalEnvironment()); var block = ts.createBlock(statements, /*multiLine*/ true); ts.setTextRange(block, node.body); @@ -57632,27 +57536,28 @@ var ts; ts.addEmitHelper(block, ts.asyncSuperHelper); } } - return block; + result = block; } else { - var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformFunctionBodyWorker(node.body)); + var expression = createAwaiterHelper(context, hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body)); var declarations = endLexicalEnvironment(); if (ts.some(declarations)) { var block = ts.convertToFunctionBody(expression); - return ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + result = ts.updateBlock(block, ts.setTextRange(ts.createNodeArray(ts.concatenate(block.statements, declarations)), block.statements)); + } + else { + result = expression; } - return expression; } + enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames; + return result; } - function transformFunctionBodyWorker(body, start) { + function transformAsyncFunctionBodyWorker(body, start) { if (ts.isBlock(body)) { - return ts.updateBlock(body, ts.visitLexicalEnvironment(body.statements, visitor, context, start)); + return ts.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start)); } else { - startLexicalEnvironment(); - var visited = ts.convertToFunctionBody(ts.visitNode(body, visitor, ts.isConciseBody)); - var declarations = endLexicalEnvironment(); - return ts.updateBlock(visited, ts.setTextRange(ts.createNodeArray(ts.concatenate(visited.statements, declarations)), visited.statements)); + return ts.convertToFunctionBody(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody)); } } function getPromiseConstructor(type) { @@ -57928,8 +57833,8 @@ var ts; function chunkObjectLiteralElements(elements) { var chunkObject; var objects = []; - for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) { - var e = elements_3[_i]; + for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) { + var e = elements_4[_i]; if (e.kind === 267 /* SpreadAssignment */) { if (chunkObject) { objects.push(ts.createObjectLiteral(chunkObject)); @@ -66088,6 +65993,7 @@ var ts; context.onSubstituteNode = onSubstituteNode; context.onEmitNode = onEmitNode; context.enableSubstitution(71 /* Identifier */); // Substitutes expression identifiers for imported symbols. + context.enableSubstitution(266 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols context.enableSubstitution(195 /* BinaryExpression */); // Substitutes assignments to exported symbols. context.enableSubstitution(193 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols. context.enableSubstitution(194 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols. @@ -67321,6 +67227,43 @@ var ts; if (hint === 1 /* Expression */) { return substituteExpression(node); } + else if (hint === 4 /* Unspecified */) { + return substituteUnspecified(node); + } + return node; + } + /** + * Substitute the node, if necessary. + * + * @param node The node to substitute. + */ + function substituteUnspecified(node) { + switch (node.kind) { + case 266 /* ShorthandPropertyAssignment */: + return substituteShorthandPropertyAssignment(node); + } + return node; + } + /** + * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol. + * + * @param node The node to substitute. + */ + function substituteShorthandPropertyAssignment(node) { + var name = node.name; + if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) { + var importDeclaration = resolver.getReferencedImportDeclaration(name); + if (importDeclaration) { + if (ts.isImportClause(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent), ts.createIdentifier("default"))), + /*location*/ node); + } + else if (ts.isImportSpecifier(importDeclaration)) { + return ts.setTextRange(ts.createPropertyAssignment(ts.getSynthesizedClone(name), ts.createPropertyAccess(ts.getGeneratedNameForNode(importDeclaration.parent.parent.parent), ts.getSynthesizedClone(importDeclaration.propertyName || importDeclaration.name))), + /*location*/ node); + } + } + } return node; } /** @@ -68189,9 +68132,9 @@ var ts; * @param tokenStartPos The start pos of the token. * @param emitCallback The callback used to emit the token. */ - function emitTokenWithSourceMap(node, token, tokenPos, emitCallback) { + function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) { if (disabled) { - return emitCallback(token, tokenPos); + return emitCallback(token, writer, tokenPos); } var emitNode = node && node.emitNode; var emitFlags = emitNode && emitNode.flags; @@ -68200,7 +68143,7 @@ var ts; if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) { emitPos(tokenPos); } - tokenPos = emitCallback(token, tokenPos); + tokenPos = emitCallback(token, writer, tokenPos); if (range) tokenPos = range.end; if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) { @@ -68945,9 +68888,9 @@ var ts; } else { errorNameNode = declaration.name; - var format = 4 /* UseTypeOfFunction */ | - 16384 /* WriteClassExpressionAsTypeLiteral */ | - (shouldUseResolverType ? 8192 /* AddUndefined */ : 0); + var format = 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 4 /* WriteDefaultSymbolWithoutName */ | + 2048 /* WriteClassExpressionAsTypeLiteral */ | + (shouldUseResolverType ? 131072 /* AddUndefined */ : 0); resolver.writeTypeOfDeclaration(declaration, enclosingDeclaration, format, writer); errorNameNode = undefined; } @@ -68961,7 +68904,7 @@ var ts; } else { errorNameNode = signature.name; - resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeReturnTypeOfSignatureDeclaration(signature, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); errorNameNode = undefined; } } @@ -69199,7 +69142,7 @@ var ts; write(tempVarName); write(": "); writer.getSymbolAccessibilityDiagnostic = function () { return diagnostic; }; - resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4 /* UseTypeOfFunction */ | 16384 /* WriteClassExpressionAsTypeLiteral */, writer); + resolver.writeTypeOfExpression(expr, enclosingDeclaration, 4096 /* UseTypeOfFunction */ | 8 /* UseStructuralFallback */ | 2048 /* WriteClassExpressionAsTypeLiteral */ | 4 /* WriteDefaultSymbolWithoutName */, writer); write(";"); writeLine(); return tempVarName; @@ -70440,7 +70383,7 @@ var ts; function writeDeclarationFile(declarationFilePath, sourceFileOrBundle, host, resolver, emitterDiagnostics, emitOnlyDtsFiles) { var emitDeclarationResult = emitDeclarations(host, resolver, emitterDiagnostics, declarationFilePath, sourceFileOrBundle, emitOnlyDtsFiles); var emitSkipped = emitDeclarationResult.reportedDeclarationError || host.isEmitBlocked(declarationFilePath) || host.getCompilerOptions().noEmit; - if (!emitSkipped) { + if (!emitSkipped || emitOnlyDtsFiles) { var sourceFiles = sourceFileOrBundle.kind === 270 /* Bundle */ ? sourceFileOrBundle.sourceFiles : [sourceFileOrBundle]; var declarationOutput = emitDeclarationResult.referencesOutput + getDeclarationOutput(emitDeclarationResult.synchronousDeclarationOutput, emitDeclarationResult.moduleElementDeclarationEmitInfo); @@ -70471,7 +70414,6 @@ var ts; /// var ts; (function (ts) { - var delimiters = createDelimiterMap(); var brackets = createBracketsMap(); /*@internal*/ /** @@ -70491,7 +70433,10 @@ var ts; var jsFilePath = options.outFile || options.out; var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = options.declaration ? ts.removeFileExtension(jsFilePath) + ".d.ts" /* Dts */ : ""; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, ts.createBundle(sourceFiles), emitOnlyDtsFiles); + if (result) { + return result; + } } } else { @@ -70500,7 +70445,10 @@ var ts; var jsFilePath = ts.getOwnEmitOutputFilePath(sourceFile, host, getOutputExtension(sourceFile, options)); var sourceMapFilePath = getSourceMapFilePath(jsFilePath, options); var declarationFilePath = !ts.isSourceFileJavaScript(sourceFile) && (emitOnlyDtsFiles || options.declaration) ? ts.getDeclarationEmitOutputFilePath(sourceFile, host) : undefined; - action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + var result = action({ jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath }, sourceFile, emitOnlyDtsFiles); + if (result) { + return result; + } } } } @@ -70633,7 +70581,7 @@ var ts; ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), compilerOptions.emitBOM, sourceFiles); // Reset state sourceMap.reset(); - writer.reset(); + writer.clear(); currentSourceFile = undefined; bundledHelpers = undefined; isOwnFileEmit = false; @@ -70699,16 +70647,29 @@ var ts; var generatedNames; // Set of names generated by the NameGenerator. var tempFlagsStack; // Stack of enclosing name generation scopes. var tempFlags; // TempFlags for the current name generation scope. + var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes. + var reservedNames; // TempFlags to reserve in nested name generation scopes. var writer; var ownWriter; + var write = writeBase; + var commitPendingSemicolon = ts.noop; + var writeSemicolon = writeSemicolonInternal; + var pendingSemicolon = false; + if (printerOptions.omitTrailingSemicolon) { + commitPendingSemicolon = commitPendingSemicolonInternal; + writeSemicolon = deferWriteSemicolon; + } + var syntheticParent = { pos: -1, end: -1 }; reset(); return { // public API printNode: printNode, + printList: printList, printFile: printFile, printBundle: printBundle, // internal API writeNode: writeNode, + writeList: writeList, writeFile: writeFile, writeBundle: writeBundle }; @@ -70731,6 +70692,10 @@ var ts; writeNode(hint, node, sourceFile, beginPrint()); return endPrint(); } + function printList(format, nodes, sourceFile) { + writeList(format, nodes, sourceFile, beginPrint()); + return endPrint(); + } function printBundle(bundle) { writeBundle(bundle, beginPrint()); return endPrint(); @@ -70746,6 +70711,16 @@ var ts; reset(); writer = previousWriter; } + function writeList(format, nodes, sourceFile, output) { + var previousWriter = writer; + setWriter(output); + if (sourceFile) { + setSourceFile(sourceFile); + } + emitList(syntheticParent, nodes, format); + reset(); + writer = previousWriter; + } function writeBundle(bundle, output) { var previousWriter = writer; setWriter(output); @@ -70773,7 +70748,7 @@ var ts; } function endPrint() { var text = ownWriter.getText(); - ownWriter.reset(); + ownWriter.clear(); return text; } function print(hint, node, sourceFile) { @@ -70799,6 +70774,7 @@ var ts; generatedNames = ts.createMap(); tempFlagsStack = []; tempFlags = 0 /* Auto */; + reservedNamesStack = []; comments.reset(); setWriter(/*output*/ undefined); } @@ -70862,7 +70838,9 @@ var ts; } function emitMappedTypeParameter(node) { emit(node.name); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emit(node.constraint); } function pipelineEmitUnspecified(node) { @@ -70871,7 +70849,7 @@ var ts; // Strict mode reserved words // Contextual keywords if (ts.isKeyword(kind)) { - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; } switch (kind) { @@ -71109,7 +71087,7 @@ var ts; return pipelineEmitExpression(trySubstituteNode(1 /* Expression */, node)); } if (ts.isToken(node)) { - writeTokenNode(node); + writeTokenNode(node, writePunctuation); return; } } @@ -71133,7 +71111,7 @@ var ts; case 101 /* TrueKeyword */: case 99 /* ThisKeyword */: case 91 /* ImportKeyword */: - writeTokenNode(node); + writeTokenNode(node, writeKeyword); return; // Expressions case 178 /* ArrayLiteralExpression */: @@ -71229,25 +71207,27 @@ var ts; var text = getLiteralTextOfNode(node); if ((printerOptions.sourceMap || printerOptions.inlineSourceMap) && (node.kind === 9 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) { - writer.writeLiteral(text); + writeLiteral(text); } else { - write(text); + // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals + writeStringLiteral(text); } } // // Identifiers // function emitIdentifier(node) { - write(getTextOfNode(node, /*includeTrivia*/ false)); - emitTypeArguments(node, node.typeArguments); + var writeText = node.symbol ? writeSymbol : write; + writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol); + emitList(node, node.typeArguments, 26896 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments } // // Names // function emitQualifiedName(node) { emitEntityName(node.left); - write("."); + writePunctuation("."); emit(node.right); } function emitEntityName(node) { @@ -71259,36 +71239,46 @@ var ts; } } function emitComputedPropertyName(node) { - write("["); + writePunctuation("["); emitExpression(node.expression); - write("]"); + writePunctuation("]"); } // // Signature elements // function emitTypeParameter(node) { emit(node.name); - emitWithPrefix(" extends ", node.constraint); - emitWithPrefix(" = ", node.default); + if (node.constraint) { + writeSpace(); + writeKeyword("extends"); + writeSpace(); + emit(node.constraint); + } + if (node.default) { + writeSpace(); + writeOperator("="); + writeSpace(); + emit(node.default); + } } function emitParameter(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitIfPresent(node.dotDotDotToken); if (node.name) { - emit(node.name); + emitNodeWithWriter(node.name, writeParameter); } emitIfPresent(node.questionToken); if (node.parent && node.parent.kind === 277 /* JSDocFunctionType */ && !node.name) { emit(node.type); } else { - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } function emitDecorator(decorator) { - write("@"); + writePunctuation("@"); emitExpression(decorator.expression); } // @@ -71297,19 +71287,19 @@ var ts; function emitPropertySignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - emit(node.name); + emitNodeWithWriter(node.name, writeProperty); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitPropertyDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emit(node.name); emitIfPresent(node.questionToken); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); - write(";"); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); + writeSemicolon(); } function emitMethodSignature(node) { emitDecorators(node, node.decorators); @@ -71318,8 +71308,8 @@ var ts; emitIfPresent(node.questionToken); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitMethodDeclaration(node) { emitDecorators(node, node.decorators); @@ -71331,13 +71321,14 @@ var ts; } function emitConstructor(node) { emitModifiers(node, node.modifiers); - write("constructor"); + writeKeyword("constructor"); emitSignatureAndBody(node, emitSignatureHead); } function emitAccessorDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write(node.kind === 154 /* GetAccessor */ ? "get " : "set "); + writeKeyword(node.kind === 154 /* GetAccessor */ ? "get" : "set"); + writeSpace(); emit(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -71346,34 +71337,37 @@ var ts; emitModifiers(node, node.modifiers); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitConstructSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitIndexSignature(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); emitParametersForIndexSignature(node, node.parameters); - emitWithPrefix(": ", node.type); - write(";"); + emitTypeAnnotation(node.type); + writeSemicolon(); } function emitSemicolonClassElement() { - write(";"); + writeSemicolon(); } // // Types // function emitTypePredicate(node) { emit(node.parameterName); - write(" is "); + writeSpace(); + writeKeyword("is"); + writeSpace(); emit(node.type); } function emitTypeReference(node) { @@ -71383,7 +71377,9 @@ var ts; function emitFunctionType(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitJSDocFunctionType(node) { @@ -71405,34 +71401,39 @@ var ts; write("="); } function emitConstructorType(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - write(" => "); + writeSpace(); + writePunctuation("=>"); + writeSpace(); emit(node.type); } function emitTypeQuery(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emit(node.exprName); } function emitTypeLiteral(node) { - write("{"); + writePunctuation("{"); var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 448 /* SingleLineTypeLiteralMembers */ : 65 /* MultiLineTypeLiteralMembers */; emitList(node, node.members, flags | 262144 /* NoSpaceIfEmpty */); - write("}"); + writePunctuation("}"); } function emitArrayType(node) { emit(node.elementType); - write("[]"); + writePunctuation("["); + writePunctuation("]"); } function emitJSDocVariadicType(node) { write("..."); emit(node.type); } function emitTupleType(node) { - write("["); + writePunctuation("["); emitList(node, node.elementTypes, 336 /* TupleTypeElements */); - write("]"); + writePunctuation("]"); } function emitUnionType(node) { emitList(node, node.types, 260 /* UnionTypeConstituents */); @@ -71441,29 +71442,29 @@ var ts; emitList(node, node.types, 264 /* IntersectionTypeConstituents */); } function emitParenthesizedType(node) { - write("("); + writePunctuation("("); emit(node.type); - write(")"); + writePunctuation(")"); } function emitThisType() { - write("this"); + writeKeyword("this"); } function emitTypeOperator(node) { - writeTokenText(node.operator); - write(" "); + writeTokenText(node.operator, writeKeyword); + writeSpace(); emit(node.type); } function emitIndexedAccessType(node) { emit(node.objectType); - write("["); + writePunctuation("["); emit(node.indexType); - write("]"); + writePunctuation("]"); } function emitMappedType(node) { var emitFlags = ts.getEmitFlags(node); - write("{"); + writePunctuation("{"); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -71471,23 +71472,24 @@ var ts; } if (node.readonlyToken) { emit(node.readonlyToken); - write(" "); + writeSpace(); } - write("["); + writePunctuation("["); pipelineEmitWithNotification(3 /* MappedTypeParameter */, node.typeParameter); - write("]"); + writePunctuation("]"); emitIfPresent(node.questionToken); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); if (emitFlags & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); decreaseIndent(); } - write("}"); + writePunctuation("}"); } function emitLiteralType(node) { emitExpression(node.literal); @@ -71496,20 +71498,24 @@ var ts; // Binding patterns // function emitObjectBindingPattern(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 262576 /* ObjectBindingPatternElements */); - write("}"); + writePunctuation("}"); } function emitArrayBindingPattern(node) { - write("["); + writePunctuation("["); emitList(node, node.elements, 262448 /* ArrayBindingPatternElements */); - write("]"); + writePunctuation("]"); } function emitBindingElement(node) { - emitWithSuffix(node.propertyName, ": "); emitIfPresent(node.dotDotDotToken); + if (node.propertyName) { + emit(node.propertyName); + writePunctuation(":"); + writeSpace(); + } emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Expressions @@ -71546,7 +71552,7 @@ var ts; emitExpression(node.expression); increaseIndentIf(indentBeforeDot); var shouldEmitDotDot = !indentBeforeDot && needsDotDotForPropertyAccess(node.expression); - write(shouldEmitDotDot ? ".." : "."); + writePunctuation(shouldEmitDotDot ? ".." : "."); increaseIndentIf(indentAfterDot); emit(node.name); decreaseIndentIf(indentBeforeDot, indentAfterDot); @@ -71572,9 +71578,9 @@ var ts; } function emitElementAccessExpression(node) { emitExpression(node.expression); - write("["); + writePunctuation("["); emitExpression(node.argumentExpression); - write("]"); + writePunctuation("]"); } function emitCallExpression(node) { emitExpression(node.expression); @@ -71582,26 +71588,27 @@ var ts; emitExpressionList(node, node.arguments, 1296 /* CallExpressionArguments */); } function emitNewExpression(node) { - write("new "); + writeKeyword("new"); + writeSpace(); emitExpression(node.expression); emitTypeArguments(node, node.typeArguments); emitExpressionList(node, node.arguments, 9488 /* NewExpressionArguments */); } function emitTaggedTemplateExpression(node) { emitExpression(node.tag); - write(" "); + writeSpace(); emitExpression(node.template); } function emitTypeAssertionExpression(node) { - write("<"); + writePunctuation("<"); emit(node.type); - write(">"); + writePunctuation(">"); emitExpression(node.expression); } function emitParenthesizedExpression(node) { - write("("); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } function emitFunctionExpression(node) { emitFunctionDeclarationOrExpression(node); @@ -71614,30 +71621,34 @@ var ts; function emitArrowFunctionHead(node) { emitTypeParameters(node, node.typeParameters); emitParametersForArrow(node, node.parameters); - emitWithPrefix(": ", node.type); - write(" "); + emitTypeAnnotation(node.type); + writeSpace(); emit(node.equalsGreaterThanToken); } function emitDeleteExpression(node) { - write("delete "); + writeKeyword("delete"); + writeSpace(); emitExpression(node.expression); } function emitTypeOfExpression(node) { - write("typeof "); + writeKeyword("typeof"); + writeSpace(); emitExpression(node.expression); } function emitVoidExpression(node) { - write("void "); + writeKeyword("void"); + writeSpace(); emitExpression(node.expression); } function emitAwaitExpression(node) { - write("await "); + writeKeyword("await"); + writeSpace(); emitExpression(node.expression); } function emitPrefixUnaryExpression(node) { - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); if (shouldEmitWhitespaceBeforeOperand(node)) { - write(" "); + writeSpace(); } emitExpression(node.operand); } @@ -71661,7 +71672,7 @@ var ts; } function emitPostfixUnaryExpression(node) { emitExpression(node.operand); - writeTokenText(node.operator); + writeTokenText(node.operator, writeOperator); } function emitBinaryExpression(node) { var isCommaOperator = node.operatorToken.kind !== 26 /* CommaToken */; @@ -71670,7 +71681,7 @@ var ts; emitExpression(node.left); increaseIndentIf(indentBeforeOperator, isCommaOperator ? " " : undefined); emitLeadingCommentsOfPosition(node.operatorToken.pos); - writeTokenNode(node.operatorToken); + writeTokenNode(node.operatorToken, writeOperator); emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts increaseIndentIf(indentAfterOperator, " "); emitExpression(node.right); @@ -71698,12 +71709,12 @@ var ts; emitList(node, node.templateSpans, 131072 /* TemplateExpressionSpans */); } function emitYieldExpression(node) { - write("yield"); + writeKeyword("yield"); emit(node.asteriskToken); - emitExpressionWithPrefix(" ", node.expression); + emitExpressionWithLeadingSpace(node.expression); } function emitSpreadExpression(node) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } function emitClassExpression(node) { @@ -71716,17 +71727,19 @@ var ts; function emitAsExpression(node) { emitExpression(node.expression); if (node.type) { - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.type); } } function emitNonNullExpression(node) { emitExpression(node.expression); - write("!"); + writeOperator("!"); } function emitMetaProperty(node) { - writeToken(node.keywordToken, node.pos); - write("."); + writeToken(node.keywordToken, node.pos, writePunctuation); + writePunctuation("."); emit(node.name); } // @@ -71740,13 +71753,13 @@ var ts; // Statements // function emitBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos, /*contextNode*/ node); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node); emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node)); // We have to call emitLeadingComments explicitly here because otherwise leading comments of the close brace token will not be emitted increaseIndent(); emitLeadingCommentsOfPosition(node.statements.end); decreaseIndent(); - writeToken(18 /* CloseBraceToken */, node.statements.end, /*contextNode*/ node); + writeToken(18 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node); } function emitBlockStatements(node, forceSingleLine) { var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 384 /* SingleLineBlockStatements */ : 65 /* MultiLineBlockStatements */; @@ -71755,27 +71768,27 @@ var ts; function emitVariableStatement(node) { emitModifiers(node, node.modifiers); emit(node.declarationList); - write(";"); + writeSemicolon(); } function emitEmptyStatement() { - write(";"); + writeSemicolon(); } function emitExpressionStatement(node) { emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitIfStatement(node) { - var openParenPos = writeToken(90 /* IfKeyword */, node.pos, node); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, node); + var openParenPos = writeToken(90 /* IfKeyword */, node.pos, writeKeyword, node); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, node); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end, node); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation, node); emitEmbeddedStatement(node, node.thenStatement); if (node.elseStatement) { writeLineOrSpace(node); - writeToken(82 /* ElseKeyword */, node.thenStatement.end, node); + writeToken(82 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node); if (node.elseStatement.kind === 212 /* IfStatement */) { - write(" "); + writeSpace(); emit(node.elseStatement); } else { @@ -71784,55 +71797,63 @@ var ts; } } function emitDoStatement(node) { - write("do"); + writeKeyword("do"); emitEmbeddedStatement(node, node.statement); if (ts.isBlock(node.statement)) { - write(" "); + writeSpace(); } else { writeLineOrSpace(node); } - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(");"); + writePunctuation(");"); } function emitWhileStatement(node) { - write("while ("); + writeKeyword("while"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos, /*contextNode*/ node); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node); emitForBinding(node.initializer); - write(";"); - emitExpressionWithPrefix(" ", node.condition); - write(";"); - emitExpressionWithPrefix(" ", node.incrementor); - write(")"); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.condition); + writeSemicolon(); + emitExpressionWithLeadingSpace(node.incrementor); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitForInStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" in "); + writeSpace(); + writeKeyword("in"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForOfStatement(node) { - var openParenPos = writeToken(88 /* ForKeyword */, node.pos); - write(" "); - emitWithSuffix(node.awaitModifier, " "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(88 /* ForKeyword */, node.pos, writeKeyword); + writeSpace(); + emitWithTrailingSpace(node.awaitModifier); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitForBinding(node.initializer); - write(" of "); + writeSpace(); + writeKeyword("of"); + writeSpace(); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); emitEmbeddedStatement(node, node.statement); } function emitForBinding(node) { @@ -71846,58 +71867,62 @@ var ts; } } function emitContinueStatement(node) { - writeToken(77 /* ContinueKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(77 /* ContinueKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } function emitBreakStatement(node) { - writeToken(72 /* BreakKeyword */, node.pos); - emitWithPrefix(" ", node.label); - write(";"); + writeToken(72 /* BreakKeyword */, node.pos, writeKeyword); + emitWithLeadingSpace(node.label); + writeSemicolon(); } - function emitTokenWithComment(token, pos, contextNode) { + function emitTokenWithComment(token, pos, writer, contextNode) { var node = contextNode && ts.getParseTreeNode(contextNode); if (node && node.kind === contextNode.kind) { pos = ts.skipTrivia(currentSourceFile.text, pos); } - pos = writeToken(token, pos, /*contextNode*/ contextNode); + pos = writeToken(token, pos, writer, /*contextNode*/ contextNode); if (node && node.kind === contextNode.kind) { emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true); } return pos; } function emitReturnStatement(node) { - emitTokenWithComment(96 /* ReturnKeyword */, node.pos, /*contextNode*/ node); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + emitTokenWithComment(96 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitWithStatement(node) { - write("with ("); + writeKeyword("with"); + writeSpace(); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); emitEmbeddedStatement(node, node.statement); } function emitSwitchStatement(node) { - var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos); - write(" "); - writeToken(19 /* OpenParenToken */, openParenPos); + var openParenPos = writeToken(98 /* SwitchKeyword */, node.pos, writeKeyword); + writeSpace(); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emitExpression(node.expression); - writeToken(20 /* CloseParenToken */, node.expression.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.expression.end, writePunctuation); + writeSpace(); emit(node.caseBlock); } function emitLabeledStatement(node) { emit(node.label); - write(": "); + writePunctuation(":"); + writeSpace(); emit(node.statement); } function emitThrowStatement(node) { - write("throw"); - emitExpressionWithPrefix(" ", node.expression); - write(";"); + writeKeyword("throw"); + emitExpressionWithLeadingSpace(node.expression); + writeSemicolon(); } function emitTryStatement(node) { - write("try "); + writeKeyword("try"); + writeSpace(); emit(node.tryBlock); if (node.catchClause) { writeLineOrSpace(node); @@ -71905,24 +71930,26 @@ var ts; } if (node.finallyBlock) { writeLineOrSpace(node); - write("finally "); + writeKeyword("finally"); + writeSpace(); emit(node.finallyBlock); } } function emitDebuggerStatement(node) { - writeToken(78 /* DebuggerKeyword */, node.pos); - write(";"); + writeToken(78 /* DebuggerKeyword */, node.pos, writeKeyword); + writeSemicolon(); } // // Declarations // function emitVariableDeclaration(node) { emit(node.name); - emitWithPrefix(": ", node.type); - emitExpressionWithPrefix(" = ", node.initializer); + emitTypeAnnotation(node.type); + emitInitializer(node.initializer); } function emitVariableDeclarationList(node) { - write(ts.isLet(node) ? "let " : ts.isConst(node) ? "const " : "var "); + writeKeyword(ts.isLet(node) ? "let" : ts.isConst(node) ? "const" : "var"); + writeSpace(); emitList(node, node.declarations, 272 /* VariableDeclarationList */); } function emitFunctionDeclaration(node) { @@ -71931,9 +71958,9 @@ var ts; function emitFunctionDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("function"); + writeKeyword("function"); emitIfPresent(node.asteriskToken); - write(" "); + writeSpace(); emitIdentifierName(node.name); emitSignatureAndBody(node, emitSignatureHead); } @@ -71963,19 +71990,19 @@ var ts; } else { emitSignatureHead(node); - write(" "); + writeSpace(); emitExpression(body); } } else { emitSignatureHead(node); - write(";"); + writeSemicolon(); } } function emitSignatureHead(node) { emitTypeParameters(node, node.typeParameters); emitParameters(node, node.parameters); - emitWithPrefix(": ", node.type); + emitTypeAnnotation(node.type); } function shouldEmitBlockFunctionBodyOnSingleLine(body) { // We must emit a function body as a single-line body in the following case: @@ -72008,7 +72035,8 @@ var ts; return true; } function emitBlockFunctionBody(body) { - write(" {"); + writeSpace(); + writePunctuation("{"); increaseIndent(); var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body) ? emitBlockFunctionBodyOnSingleLine @@ -72020,7 +72048,7 @@ var ts; emitBlockFunctionBody(body); } decreaseIndent(); - writeToken(18 /* CloseBraceToken */, body.statements.end, body); + writeToken(18 /* CloseBraceToken */, body.statements.end, writePunctuation, body); } function emitBlockFunctionBodyOnSingleLine(body) { emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true); @@ -72045,17 +72073,21 @@ var ts; function emitClassDeclarationOrExpression(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("class"); - emitNodeWithPrefix(" ", node.name, emitIdentifierName); + writeKeyword("class"); + if (node.name) { + writeSpace(); + emitIdentifierName(node.name); + } var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */; if (indentedFlag) { increaseIndent(); } emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* ClassHeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* ClassMembers */); - write("}"); + writePunctuation("}"); if (indentedFlag) { decreaseIndent(); } @@ -72063,66 +72095,77 @@ var ts; function emitInterfaceDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("interface "); + writeKeyword("interface"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); emitList(node, node.heritageClauses, 256 /* HeritageClauses */); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 65 /* InterfaceMembers */); - write("}"); + writePunctuation("}"); } function emitTypeAliasDeclaration(node) { emitDecorators(node, node.decorators); emitModifiers(node, node.modifiers); - write("type "); + writeKeyword("type"); + writeSpace(); emit(node.name); emitTypeParameters(node, node.typeParameters); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emit(node.type); - write(";"); + writeSemicolon(); } function emitEnumDeclaration(node) { emitModifiers(node, node.modifiers); - write("enum "); + writeKeyword("enum"); + writeSpace(); emit(node.name); - write(" {"); + writeSpace(); + writePunctuation("{"); emitList(node, node.members, 81 /* EnumMembers */); - write("}"); + writePunctuation("}"); } function emitModuleDeclaration(node) { emitModifiers(node, node.modifiers); if (~node.flags & 512 /* GlobalAugmentation */) { - write(node.flags & 16 /* Namespace */ ? "namespace " : "module "); + writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module"); + writeSpace(); } emit(node.name); var body = node.body; while (body.kind === 234 /* ModuleDeclaration */) { - write("."); + writePunctuation("."); emit(body.name); body = body.body; } - write(" "); + writeSpace(); emit(body); } function emitModuleBlock(node) { pushNameGenerationScope(node); - write("{"); + writePunctuation("{"); emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node)); - write("}"); + writePunctuation("}"); popNameGenerationScope(node); } function emitCaseBlock(node) { - writeToken(17 /* OpenBraceToken */, node.pos); + writeToken(17 /* OpenBraceToken */, node.pos, writePunctuation); emitList(node, node.clauses, 65 /* CaseBlockClauses */); - writeToken(18 /* CloseBraceToken */, node.clauses.end); + writeToken(18 /* CloseBraceToken */, node.clauses.end, writePunctuation); } function emitImportEqualsDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); emit(node.name); - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitModuleReference(node.moduleReference); - write(";"); + writeSemicolon(); } function emitModuleReference(node) { if (node.kind === 71 /* Identifier */) { @@ -72134,23 +72177,30 @@ var ts; } function emitImportDeclaration(node) { emitModifiers(node, node.modifiers); - write("import "); + writeKeyword("import"); + writeSpace(); if (node.importClause) { emit(node.importClause); - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); } emitExpression(node.moduleSpecifier); - write(";"); + writeSemicolon(); } function emitImportClause(node) { emit(node.name); if (node.name && node.namedBindings) { - write(", "); + writePunctuation(","); + writeSpace(); } emit(node.namedBindings); } function emitNamespaceImport(node) { - write("* as "); + writePunctuation("*"); + writeSpace(); + writeKeyword("as"); + writeSpace(); emit(node.name); } function emitNamedImports(node) { @@ -72160,28 +72210,44 @@ var ts; emitImportOrExportSpecifier(node); } function emitExportAssignment(node) { - write(node.isExportEquals ? "export = " : "export default "); + writeKeyword("export"); + writeSpace(); + if (node.isExportEquals) { + writeOperator("="); + } + else { + writeKeyword("default"); + } + writeSpace(); emitExpression(node.expression); - write(";"); + writeSemicolon(); } function emitExportDeclaration(node) { - write("export "); + writeKeyword("export"); + writeSpace(); if (node.exportClause) { emit(node.exportClause); } else { - write("*"); + writePunctuation("*"); } if (node.moduleSpecifier) { - write(" from "); + writeSpace(); + writeKeyword("from"); + writeSpace(); emitExpression(node.moduleSpecifier); } - write(";"); + writeSemicolon(); } function emitNamespaceExportDeclaration(node) { - write("export as namespace "); + writeKeyword("export"); + writeSpace(); + writeKeyword("as"); + writeSpace(); + writeKeyword("namespace"); + writeSpace(); emit(node.name); - write(";"); + writeSemicolon(); } function emitNamedExports(node) { emitNamedImportsOrExports(node); @@ -72190,14 +72256,16 @@ var ts; emitImportOrExportSpecifier(node); } function emitNamedImportsOrExports(node) { - write("{"); + writePunctuation("{"); emitList(node, node.elements, 432 /* NamedImportsOrExportsElements */); - write("}"); + writePunctuation("}"); } function emitImportOrExportSpecifier(node) { if (node.propertyName) { emit(node.propertyName); - write(" as "); + writeSpace(); + writeKeyword("as"); + writeSpace(); } emit(node.name); } @@ -72205,9 +72273,10 @@ var ts; // Module references // function emitExternalModuleReference(node) { - write("require("); + writeKeyword("require"); + writePunctuation("("); emitExpression(node.expression); - write(")"); + writePunctuation(")"); } // // JSX @@ -72218,14 +72287,14 @@ var ts; emit(node.closingElement); } function emitJsxSelfClosingElement(node) { - write("<"); + writePunctuation("<"); emitJsxTagName(node.tagName); - write(" "); + writeSpace(); // We are checking here so we won't re-enter the emiting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { emit(node.attributes); } - write("/>"); + writePunctuation("/>"); } function emitJsxFragment(node) { emit(node.openingFragment); @@ -72233,45 +72302,46 @@ var ts; emit(node.closingFragment); } function emitJsxOpeningElementOrFragment(node) { - write("<"); + writePunctuation("<"); if (ts.isJsxOpeningElement(node)) { emitJsxTagName(node.tagName); // We are checking here so we won't re-enter the emitting pipeline and emit extra sourcemap if (node.attributes.properties && node.attributes.properties.length > 0) { - write(" "); + writeSpace(); emit(node.attributes); } } - write(">"); + writePunctuation(">"); } function emitJsxText(node) { + commitPendingSemicolon(); writer.writeLiteral(getTextOfNode(node, /*includeTrivia*/ true)); } function emitJsxClosingElementOrFragment(node) { - write(""); + writePunctuation(">"); } function emitJsxAttributes(node) { emitList(node, node.properties, 131328 /* JsxElementAttributes */); } function emitJsxAttribute(node) { emit(node.name); - emitWithPrefix("=", node.initializer); + emitNodeWithPrefix("=", writePunctuation, node.initializer, emit); } function emitJsxSpreadAttribute(node) { - write("{..."); + writePunctuation("{..."); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } function emitJsxExpression(node) { if (node.expression) { - write("{"); + writePunctuation("{"); emitIfPresent(node.dotDotDotToken); emitExpression(node.expression); - write("}"); + writePunctuation("}"); } } function emitJsxTagName(node) { @@ -72286,13 +72356,15 @@ var ts; // Clauses // function emitCaseClause(node) { - write("case "); + writeKeyword("case"); + writeSpace(); emitExpression(node.expression); - write(":"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitDefaultClause(node) { - write("default:"); + writeKeyword("default"); + writePunctuation(":"); emitCaseOrDefaultClauseStatements(node, node.statements); } function emitCaseOrDefaultClauseStatements(parentNode, statements) { @@ -72319,25 +72391,25 @@ var ts; } var format = 81985 /* CaseOrDefaultClauseStatements */; if (emitAsSingleStatement) { - write(" "); + writeSpace(); format &= ~(1 /* MultiLine */ | 64 /* Indented */); } emitList(parentNode, statements, format); } function emitHeritageClause(node) { - write(" "); - writeTokenText(node.token); - write(" "); + writeSpace(); + writeTokenText(node.token, writeKeyword); + writeSpace(); emitList(node, node.types, 272 /* HeritageClauseTypes */); } function emitCatchClause(node) { - var openParenPos = writeToken(74 /* CatchKeyword */, node.pos); - write(" "); + var openParenPos = writeToken(74 /* CatchKeyword */, node.pos, writeKeyword); + writeSpace(); if (node.variableDeclaration) { - writeToken(19 /* OpenParenToken */, openParenPos); + writeToken(19 /* OpenParenToken */, openParenPos, writePunctuation); emit(node.variableDeclaration); - writeToken(20 /* CloseParenToken */, node.variableDeclaration.end); - write(" "); + writeToken(20 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation); + writeSpace(); } emit(node.block); } @@ -72346,7 +72418,8 @@ var ts; // function emitPropertyAssignment(node) { emit(node.name); - write(": "); + writePunctuation(":"); + writeSpace(); // This is to ensure that we emit comment in the following case: // For example: // obj = { @@ -72364,13 +72437,15 @@ var ts; function emitShorthandPropertyAssignment(node) { emit(node.name); if (node.objectAssignmentInitializer) { - write(" = "); + writeSpace(); + writePunctuation("="); + writeSpace(); emitExpression(node.objectAssignmentInitializer); } } function emitSpreadAssignment(node) { if (node.expression) { - write("..."); + writePunctuation("..."); emitExpression(node.expression); } } @@ -72379,7 +72454,7 @@ var ts; // function emitEnumMember(node) { emit(node.name); - emitExpressionWithPrefix(" = ", node.initializer); + emitInitializer(node.initializer); } // // Top-level nodes @@ -72477,33 +72552,60 @@ var ts; // // Helpers // + function emitNodeWithWriter(node, writer) { + var savedWrite = write; + write = writer; + emit(node); + write = savedWrite; + } function emitModifiers(node, modifiers) { if (modifiers && modifiers.length) { emitList(node, modifiers, 131328 /* Modifiers */); - write(" "); + writeSpace(); } } - function emitWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emit); - } - function emitExpressionWithPrefix(prefix, node) { - emitNodeWithPrefix(prefix, node, emitExpression); - } - function emitNodeWithPrefix(prefix, node, emit) { + function emitTypeAnnotation(node) { if (node) { - write(prefix); + writePunctuation(":"); + writeSpace(); emit(node); } } - function emitWithSuffix(node, suffix) { + function emitInitializer(node) { + if (node) { + writeSpace(); + writeOperator("="); + writeSpace(); + emitExpression(node); + } + } + function emitNodeWithPrefix(prefix, prefixWriter, node, emit) { + if (node) { + prefixWriter(prefix); + emit(node); + } + } + function emitWithLeadingSpace(node) { + if (node) { + writeSpace(); + emit(node); + } + } + function emitExpressionWithLeadingSpace(node) { + if (node) { + writeSpace(); + emitExpression(node); + } + } + function emitWithTrailingSpace(node) { if (node) { emit(node); - write(suffix); + writeSpace(); } } function emitEmbeddedStatement(parent, node) { if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) { - write(" "); + writeSpace(); emit(node); } else { @@ -72517,13 +72619,16 @@ var ts; emitList(parentNode, decorators, 24577 /* Decorators */); } function emitTypeArguments(parentNode, typeArguments) { - emitList(parentNode, typeArguments, 26960 /* TypeArguments */); + emitList(parentNode, typeArguments, 26896 /* TypeArguments */); } function emitTypeParameters(parentNode, typeParameters) { - emitList(parentNode, typeParameters, 26960 /* TypeParameters */); + if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { + return emitTypeArguments(parentNode, parentNode.typeArguments); + } + emitList(parentNode, typeParameters, 26896 /* TypeParameters */); } function emitParameters(parentNode, parameters) { - emitList(parentNode, parameters, 1360 /* Parameters */); + emitList(parentNode, parameters, 1296 /* Parameters */); } function canEmitSimpleArrowHead(parentNode, parameters) { var parameter = ts.singleOrUndefined(parameters); @@ -72543,7 +72648,7 @@ var ts; } function emitParametersForArrow(parentNode, parameters) { if (canEmitSimpleArrowHead(parentNode, parameters)) { - emitList(parentNode, parameters, 1360 /* Parameters */ & ~1024 /* Parenthesis */); + emitList(parentNode, parameters, 1296 /* Parameters */ & ~1024 /* Parenthesis */); } else { emitParameters(parentNode, parameters); @@ -72558,6 +72663,23 @@ var ts; function emitExpressionList(parentNode, children, format, start, count) { emitNodeList(emitExpression, parentNode, children, format, start, count); } + function writeDelimiter(format) { + switch (format & 28 /* DelimitersMask */) { + case 0 /* None */: + break; + case 16 /* CommaDelimited */: + writePunctuation(","); + break; + case 4 /* BarDelimited */: + writeSpace(); + writePunctuation("|"); + break; + case 8 /* AmpersandDelimited */: + writeSpace(); + writePunctuation("&"); + break; + } + } function emitNodeList(emit, parentNode, children, format, start, count) { if (start === void 0) { start = 0; } if (count === void 0) { count = children ? children.length - start : 0; } @@ -72576,7 +72698,7 @@ var ts; return; } if (format & 7680 /* BracketsMask */) { - write(getOpeningBracket(format)); + writePunctuation(getOpeningBracket(format)); } if (onBeforeEmitNodeArray) { onBeforeEmitNodeArray(children); @@ -72587,7 +72709,7 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */ && !(format & 262144 /* NoSpaceIfEmpty */)) { - write(" "); + writeSpace(); } } else { @@ -72599,7 +72721,7 @@ var ts; shouldEmitInterveningComments = false; } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } // Increase the indent, if requested. if (format & 64 /* Indented */) { @@ -72608,7 +72730,6 @@ var ts; // Emit each child. var previousSibling = void 0; var shouldDecreaseIndentAfterEmit = void 0; - var delimiter = getDelimiter(format); for (var i = 0; i < count; i++) { var child = children[start + i]; // Write the delimiter if this is not the first node. @@ -72619,10 +72740,10 @@ var ts; // a // /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline // , - if (delimiter && previousSibling.end !== parentNode.end) { + if (format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end) { emitLeadingCommentsOfPosition(previousSibling.end); } - write(delimiter); + writeDelimiter(format); // Write either a line terminator or whitespace to separate the elements. if (shouldWriteSeparatingLineTerminator(previousSibling, child, format)) { // If a synthesized node in a single-line list starts on a new @@ -72635,7 +72756,7 @@ var ts; shouldEmitInterveningComments = false; } else if (previousSibling && format & 256 /* SpaceBetweenSiblings */) { - write(" "); + writeSpace(); } } // Emit this child. @@ -72658,7 +72779,7 @@ var ts; // Write a trailing comma, if requested. var hasTrailingComma = (format & 32 /* AllowTrailingComma */) && children.hasTrailingComma; if (format & 16 /* CommaDelimited */ && hasTrailingComma) { - write(","); + writePunctuation(","); } // Emit any trailing comment of the last element in the list // i.e @@ -72666,7 +72787,7 @@ var ts; // 2 // /* end of element 2 */ // ]; - if (previousSibling && delimiter && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { + if (previousSibling && format & 28 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) { emitLeadingCommentsOfPosition(previousSibling.end); } // Decrease the indent, if requested. @@ -72678,50 +72799,102 @@ var ts; writeLine(); } else if (format & 128 /* SpaceBetweenBraces */) { - write(" "); + writeSpace(); } } if (onAfterEmitNodeArray) { onAfterEmitNodeArray(children); } if (format & 7680 /* BracketsMask */) { - write(getClosingBracket(format)); + writePunctuation(getClosingBracket(format)); } } - function write(s) { + function commitPendingSemicolonInternal() { + if (pendingSemicolon) { + writeSemicolonInternal(); + pendingSemicolon = false; + } + } + function writeLiteral(s) { + commitPendingSemicolon(); + writer.writeLiteral(s); + } + function writeStringLiteral(s) { + commitPendingSemicolon(); + writer.writeStringLiteral(s); + } + function writeBase(s) { + commitPendingSemicolon(); writer.write(s); } + function writeSymbol(s, sym) { + commitPendingSemicolon(); + writer.writeSymbol(s, sym); + } + function writePunctuation(s) { + commitPendingSemicolon(); + writer.writePunctuation(s); + } + function deferWriteSemicolon() { + pendingSemicolon = true; + } + function writeSemicolonInternal() { + writer.writePunctuation(";"); + } + function writeKeyword(s) { + commitPendingSemicolon(); + writer.writeKeyword(s); + } + function writeOperator(s) { + commitPendingSemicolon(); + writer.writeOperator(s); + } + function writeParameter(s) { + commitPendingSemicolon(); + writer.writeParameter(s); + } + function writeSpace() { + commitPendingSemicolon(); + writer.writeSpace(" "); + } + function writeProperty(s) { + commitPendingSemicolon(); + writer.writeProperty(s); + } function writeLine() { + commitPendingSemicolon(); writer.writeLine(); } function increaseIndent() { + commitPendingSemicolon(); writer.increaseIndent(); } function decreaseIndent() { + commitPendingSemicolon(); writer.decreaseIndent(); } - function writeToken(token, pos, contextNode) { + function writeToken(token, pos, writer, contextNode) { return onEmitSourceMapOfToken - ? onEmitSourceMapOfToken(contextNode, token, pos, writeTokenText) - : writeTokenText(token, pos); + ? onEmitSourceMapOfToken(contextNode, token, writer, pos, writeTokenText) + : writeTokenText(token, writer, pos); } - function writeTokenNode(node) { + function writeTokenNode(node, writer) { if (onBeforeEmitToken) { onBeforeEmitToken(node); } - write(ts.tokenToString(node.kind)); + writer(ts.tokenToString(node.kind)); if (onAfterEmitToken) { onAfterEmitToken(node); } } - function writeTokenText(token, pos) { + function writeTokenText(token, writer, pos) { var tokenString = ts.tokenToString(token); - write(tokenString); + writer(tokenString); return pos < 0 ? pos : pos + tokenString.length; } function writeLineOrSpace(node) { if (ts.getEmitFlags(node) & 1 /* SingleLine */) { - write(" "); + writeSpace(); } else { writeLine(); @@ -72912,6 +73085,7 @@ var ts; } tempFlagsStack.push(tempFlags); tempFlags = 0; + reservedNamesStack.push(reservedNames); } /** * Pop the current name generation scope. @@ -72921,15 +73095,22 @@ var ts; return; } tempFlags = tempFlagsStack.pop(); + reservedNames = reservedNamesStack.pop(); + } + function reserveNameInNestedScopes(name) { + if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) { + reservedNames = ts.createMap(); + } + reservedNames.set(name, true); } /** * Generate the text for a generated identifier. */ function generateName(name) { - if (name.autoGenerateKind === 4 /* Node */) { + 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.skipNameGenerationScope) { + if (name.autoGenerateFlags & 8 /* SkipNameGenerationScope */) { var savedTempFlags = tempFlags; popNameGenerationScope(/*node*/ undefined); var result = generateNameCached(getNodeForGeneratedName(name)); @@ -72959,7 +73140,8 @@ var ts; function isUniqueName(name) { return !(hasGlobalName && hasGlobalName(name)) && !currentSourceFile.identifiers.has(name) - && !generatedNames.has(name); + && !generatedNames.has(name) + && !(reservedNames && reservedNames.has(name)); } /** * Returns a value indicating whether a name is unique within a container. @@ -72981,11 +73163,14 @@ var ts; * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name. * Note that names generated by makeTempVariableName and makeUniqueName will never conflict. */ - function makeTempVariableName(flags) { + function makeTempVariableName(flags, reservedInNestedScopes) { if (flags && !(tempFlags & flags)) { var name = flags === 268435456 /* _i */ ? "_i" : "_n"; if (isUniqueName(name)) { tempFlags |= flags; + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -72998,6 +73183,9 @@ var ts; ? "_" + String.fromCharCode(97 /* a */ + count) : "_" + (count - 26); if (isUniqueName(name)) { + if (reservedInNestedScopes) { + reserveNameInNestedScopes(name); + } return name; } } @@ -73090,11 +73278,11 @@ var ts; * Generates a unique identifier for a node. */ function makeName(name) { - switch (name.autoGenerateKind) { + switch (name.autoGenerateFlags & 7 /* KindMask */) { case 1 /* Auto */: - return makeTempVariableName(0 /* Auto */); + return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 2 /* Loop */: - return makeTempVariableName(268435456 /* _i */); + return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 16 /* ReservedInNestedScopes */)); case 3 /* Unique */: return makeUniqueName(ts.idText(name)); } @@ -73112,7 +73300,7 @@ var ts; // if "node" is a different generated name (having a different // "autoGenerateId"), use it and stop traversing. if (ts.isIdentifier(node) - && node.autoGenerateKind === 4 /* Node */ + && node.autoGenerateFlags === 4 /* Node */ && node.autoGenerateId !== autoGenerateId) { break; } @@ -73123,17 +73311,6 @@ var ts; } } ts.createPrinter = createPrinter; - function createDelimiterMap() { - var delimiters = []; - delimiters[0 /* None */] = ""; - delimiters[16 /* CommaDelimited */] = ","; - delimiters[4 /* BarDelimited */] = " |"; - delimiters[8 /* AmpersandDelimited */] = " &"; - return delimiters; - } - function getDelimiter(format) { - return delimiters[format & 28 /* DelimitersMask */]; - } function createBracketsMap() { var brackets = []; brackets[512 /* Braces */] = ["{", "}"]; @@ -73155,474 +73332,10 @@ var ts; TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask"; TempFlags[TempFlags["_i"] = 268435456] = "_i"; })(TempFlags || (TempFlags = {})); - var ListFormat; - (function (ListFormat) { - ListFormat[ListFormat["None"] = 0] = "None"; - // Line separators - ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine"; - ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine"; - ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines"; - ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask"; - // Delimiters - 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"; - // Whitespace - ListFormat[ListFormat["Indented"] = 64] = "Indented"; - ListFormat[ListFormat["SpaceBetweenBraces"] = 128] = "SpaceBetweenBraces"; - ListFormat[ListFormat["SpaceBetweenSiblings"] = 256] = "SpaceBetweenSiblings"; - // Brackets/Braces - 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"; - // Other - 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"; - // Precomputed Formats - ListFormat[ListFormat["Modifiers"] = 131328] = "Modifiers"; - ListFormat[ListFormat["HeritageClauses"] = 256] = "HeritageClauses"; - ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 448] = "SingleLineTypeLiteralMembers"; - ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 65] = "MultiLineTypeLiteralMembers"; - ListFormat[ListFormat["TupleTypeElements"] = 336] = "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"] = 256] = "ClassHeritageClauses"; - ListFormat[ListFormat["ClassMembers"] = 65] = "ClassMembers"; - ListFormat[ListFormat["InterfaceMembers"] = 65] = "InterfaceMembers"; - ListFormat[ListFormat["EnumMembers"] = 81] = "EnumMembers"; - ListFormat[ListFormat["CaseBlockClauses"] = 65] = "CaseBlockClauses"; - ListFormat[ListFormat["NamedImportsOrExportsElements"] = 432] = "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"] = 26960] = "TypeArguments"; - ListFormat[ListFormat["TypeParameters"] = 26960] = "TypeParameters"; - ListFormat[ListFormat["Parameters"] = 1360] = "Parameters"; - ListFormat[ListFormat["IndexSignatureParameters"] = 4432] = "IndexSignatureParameters"; - })(ListFormat || (ListFormat = {})); -})(ts || (ts = {})); -/// -/* @internal */ -var ts; -(function (ts) { - function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { - var outputFiles = []; - var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); - return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; - function writeFile(fileName, text, writeByteOrderMark) { - outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); - } - } - ts.getFileEmitOutput = getFileEmitOutput; - function createBuilder(options) { - var isModuleEmit; - var fileInfos = ts.createMap(); - var semanticDiagnosticsPerFile = ts.createMap(); - /** The map has key by source file's path that has been changed */ - var changedFilesSet = ts.createMap(); - var hasShapeChanged = ts.createMap(); - var allFilesExcludingDefaultLibraryFile; - var emitHandler; - return { - updateProgram: updateProgram, - getFilesAffectedBy: getFilesAffectedBy, - emitChangedFiles: emitChangedFiles, - getSemanticDiagnostics: getSemanticDiagnostics, - clear: clear - }; - function createProgramGraph(program) { - var currentIsModuleEmit = program.getCompilerOptions().module !== ts.ModuleKind.None; - if (isModuleEmit !== currentIsModuleEmit) { - isModuleEmit = currentIsModuleEmit; - emitHandler = isModuleEmit ? getModuleEmitHandler() : getNonModuleEmitHandler(); - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - } - hasShapeChanged.clear(); - allFilesExcludingDefaultLibraryFile = undefined; - ts.mutateMap(fileInfos, ts.arrayToMap(program.getSourceFiles(), function (sourceFile) { return sourceFile.path; }), { - // Add new file info - createNewValue: function (_path, sourceFile) { return addNewFileInfo(program, sourceFile); }, - // Remove existing file info - onDeleteValue: removeExistingFileInfo, - // We will update in place instead of deleting existing value and adding new one - onExistingValue: function (existingInfo, sourceFile) { return updateExistingFileInfo(program, existingInfo, sourceFile); } - }); - } - function registerChangedFile(path) { - changedFilesSet.set(path, true); - // All changed files need to re-evaluate its semantic diagnostics - semanticDiagnosticsPerFile.delete(path); - } - function addNewFileInfo(program, sourceFile) { - registerChangedFile(sourceFile.path); - emitHandler.onAddSourceFile(program, sourceFile); - return { version: sourceFile.version, signature: undefined }; - } - function removeExistingFileInfo(_existingFileInfo, path) { - // Since we dont need to track removed file as changed file - // We can just remove its diagnostics - changedFilesSet.delete(path); - semanticDiagnosticsPerFile.delete(path); - emitHandler.onRemoveSourceFile(path); - } - function updateExistingFileInfo(program, existingInfo, sourceFile) { - if (existingInfo.version !== sourceFile.version) { - registerChangedFile(sourceFile.path); - existingInfo.version = sourceFile.version; - emitHandler.onUpdateSourceFile(program, sourceFile); - } - else if (emitHandler.onUpdateSourceFileWithSameVersion(program, sourceFile)) { - registerChangedFile(sourceFile.path); - } - } - function ensureProgramGraph(program) { - if (!emitHandler) { - createProgramGraph(program); - } - } - function updateProgram(newProgram) { - if (emitHandler) { - createProgramGraph(newProgram); - } - } - function getFilesAffectedBy(program, path) { - ensureProgramGraph(program); - var sourceFile = program.getSourceFileByPath(path); - if (!sourceFile) { - return ts.emptyArray; - } - if (!updateShapeSignature(program, sourceFile)) { - return [sourceFile]; - } - return emitHandler.getFilesAffectedByUpdatedShape(program, sourceFile); - } - function emitChangedFiles(program, writeFileCallback) { - ensureProgramGraph(program); - var compilerOptions = program.getCompilerOptions(); - if (!changedFilesSet.size) { - return ts.emptyArray; - } - // With --out or --outFile all outputs go into single file, do it only once - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - changedFilesSet.clear(); - return [program.emit(/*targetSourceFile*/ undefined, writeFileCallback)]; - } - var seenFiles = ts.createMap(); - var result; - changedFilesSet.forEach(function (_true, path) { - // Get the affected Files by this program - var affectedFiles = getFilesAffectedBy(program, path); - affectedFiles.forEach(function (affectedFile) { - // Affected files shouldnt have cached diagnostics - semanticDiagnosticsPerFile.delete(affectedFile.path); - if (!seenFiles.has(affectedFile.path)) { - seenFiles.set(affectedFile.path, true); - // Emit the affected file - (result || (result = [])).push(program.emit(affectedFile, writeFileCallback)); - } - }); - }); - changedFilesSet.clear(); - return result || ts.emptyArray; - } - function getSemanticDiagnostics(program, cancellationToken) { - ensureProgramGraph(program); - ts.Debug.assert(changedFilesSet.size === 0); - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions.outFile || compilerOptions.out) { - ts.Debug.assert(semanticDiagnosticsPerFile.size === 0); - // We dont need to cache the diagnostics just return them from program - return program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken); - } - var diagnostics; - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken)); - } - return diagnostics || ts.emptyArray; - } - function getSemanticDiagnosticsOfFile(program, sourceFile, cancellationToken) { - var path = sourceFile.path; - var cachedDiagnostics = semanticDiagnosticsPerFile.get(path); - // Report the semantic diagnostics from the cache if we already have those diagnostics present - if (cachedDiagnostics) { - return cachedDiagnostics; - } - // Diagnostics werent cached, get them from program, and cache the result - var diagnostics = program.getSemanticDiagnostics(sourceFile, cancellationToken); - semanticDiagnosticsPerFile.set(path, diagnostics); - return diagnostics; - } - function clear() { - isModuleEmit = undefined; - emitHandler = undefined; - fileInfos.clear(); - semanticDiagnosticsPerFile.clear(); - changedFilesSet.clear(); - hasShapeChanged.clear(); - } - /** - * For script files that contains only ambient external modules, although they are not actually external module files, - * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, - * there are no point to rebuild all script files if these special files have changed. However, if any statement - * in the file is not ambient external module, we treat it as a regular script file. - */ - function containsOnlyAmbientModules(sourceFile) { - for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { - var statement = _a[_i]; - if (!ts.isModuleWithStringLiteralName(statement)) { - return false; - } - } - return true; - } - /** - * @return {boolean} indicates if the shape signature has changed since last update. - */ - function updateShapeSignature(program, sourceFile) { - ts.Debug.assert(!!sourceFile); - // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate - if (hasShapeChanged.has(sourceFile.path)) { - return false; - } - hasShapeChanged.set(sourceFile.path, true); - var info = fileInfos.get(sourceFile.path); - ts.Debug.assert(!!info); - var prevSignature = info.signature; - var latestSignature; - if (sourceFile.isDeclarationFile) { - latestSignature = sourceFile.version; - info.signature = latestSignature; - } - else { - var emitOutput = getFileEmitOutput(program, sourceFile, /*emitOnlyDtsFiles*/ true); - if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { - latestSignature = options.computeHash(emitOutput.outputFiles[0].text); - info.signature = latestSignature; - } - else { - latestSignature = prevSignature; - } - } - return !prevSignature || latestSignature !== prevSignature; - } - /** - * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true - */ - function getReferencedFiles(program, sourceFile) { - var referencedFiles; - // We need to use a set here since the code can contain the same import twice, - // but that will only be one dependency. - // To avoid invernal conversion, the key of the referencedFiles map must be of type Path - if (sourceFile.imports && sourceFile.imports.length > 0) { - var checker = program.getTypeChecker(); - for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { - var importName = _a[_i]; - var symbol = checker.getSymbolAtLocation(importName); - if (symbol && symbol.declarations && symbol.declarations[0]) { - var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); - if (declarationSourceFile) { - addReferencedFile(declarationSourceFile.path); - } - } - } - } - var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); - // Handle triple slash references - if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { - for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { - var referencedFile = _c[_b]; - var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(referencedPath); - } - } - // Handle type reference directives - if (sourceFile.resolvedTypeReferenceDirectiveNames) { - sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { - if (!resolvedTypeReferenceDirective) { - return; - } - var fileName = resolvedTypeReferenceDirective.resolvedFileName; - var typeFilePath = ts.toPath(fileName, sourceFileDirectory, options.getCanonicalFileName); - addReferencedFile(typeFilePath); - }); - } - return referencedFiles; - function addReferencedFile(referencedPath) { - if (!referencedFiles) { - referencedFiles = ts.createMap(); - } - referencedFiles.set(referencedPath, true); - } - } - /** - * Gets all files of the program excluding the default library file - */ - function getAllFilesExcludingDefaultLibraryFile(program, firstSourceFile) { - // Use cached result - if (allFilesExcludingDefaultLibraryFile) { - return allFilesExcludingDefaultLibraryFile; - } - var result; - addSourceFile(firstSourceFile); - for (var _i = 0, _a = program.getSourceFiles(); _i < _a.length; _i++) { - var sourceFile = _a[_i]; - if (sourceFile !== firstSourceFile) { - addSourceFile(sourceFile); - } - } - allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; - return allFilesExcludingDefaultLibraryFile; - function addSourceFile(sourceFile) { - if (!program.isSourceFileDefaultLibrary(sourceFile)) { - (result || (result = [])).push(sourceFile); - } - } - } - function getNonModuleEmitHandler() { - return { - onAddSourceFile: ts.noop, - onRemoveSourceFile: ts.noop, - onUpdateSourceFile: ts.noop, - onUpdateSourceFileWithSameVersion: ts.returnFalse, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function getFilesAffectedByUpdatedShape(program, sourceFile) { - var options = program.getCompilerOptions(); - // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, - // so returning the file itself is good enough. - if (options && (options.out || options.outFile)) { - return [sourceFile]; - } - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - } - function getModuleEmitHandler() { - var references = ts.createMap(); - return { - onAddSourceFile: setReferences, - onRemoveSourceFile: onRemoveSourceFile, - onUpdateSourceFile: updateReferences, - onUpdateSourceFileWithSameVersion: updateReferencesTrackingChangedReferences, - getFilesAffectedByUpdatedShape: getFilesAffectedByUpdatedShape - }; - function setReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - } - function updateReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (newReferences) { - references.set(sourceFile.path, newReferences); - } - else { - references.delete(sourceFile.path); - } - } - function updateReferencesTrackingChangedReferences(program, sourceFile) { - var newReferences = getReferencedFiles(program, sourceFile); - if (!newReferences) { - // Changed if we had references - return references.delete(sourceFile.path); - } - var oldReferences = references.get(sourceFile.path); - references.set(sourceFile.path, newReferences); - if (!oldReferences || oldReferences.size !== newReferences.size) { - return true; - } - // If there are any new references that werent present previously there is change - return ts.forEachEntry(newReferences, function (_true, referencedPath) { return !oldReferences.delete(referencedPath); }) || - // Otherwise its changed if there are more references previously than now - !!oldReferences.size; - } - function onRemoveSourceFile(removedFilePath) { - // Remove existing references - references.forEach(function (referencesInFile, filePath) { - if (referencesInFile.has(removedFilePath)) { - // add files referencing the removedFilePath, as changed files too - var referencedByInfo = fileInfos.get(filePath); - if (referencedByInfo) { - registerChangedFile(filePath); - } - } - }); - // Delete the entry for the removed file path - references.delete(removedFilePath); - } - function getReferencedByPaths(referencedFilePath) { - return ts.arrayFrom(ts.mapDefinedIterator(references.entries(), function (_a) { - var filePath = _a[0], referencesInFile = _a[1]; - return referencesInFile.has(referencedFilePath) ? filePath : undefined; - })); - } - function getFilesAffectedByUpdatedShape(program, sourceFile) { - if (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile)) { - return getAllFilesExcludingDefaultLibraryFile(program, sourceFile); - } - var compilerOptions = program.getCompilerOptions(); - if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { - return [sourceFile]; - } - // Now we need to if each file in the referencedBy list has a shape change as well. - // Because if so, its own referencedBy files need to be saved as well to make the - // emitting result consistent with files on disk. - var seenFileNamesMap = ts.createMap(); - // Start with the paths this file was referenced by - var path = sourceFile.path; - seenFileNamesMap.set(path, sourceFile); - var queue = getReferencedByPaths(path); - while (queue.length > 0) { - var currentPath = queue.pop(); - if (!seenFileNamesMap.has(currentPath)) { - var currentSourceFile = program.getSourceFileByPath(currentPath); - seenFileNamesMap.set(currentPath, currentSourceFile); - if (currentSourceFile && updateShapeSignature(program, currentSourceFile)) { - queue.push.apply(queue, getReferencedByPaths(currentPath)); - } - } - } - // Return array of values that needs emit - return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); - } - } - } - ts.createBuilder = createBuilder; })(ts || (ts = {})); /// /// /// -/// var ts; (function (ts) { var ignoreDiagnosticCommentRegEx = /(^\s*$)|(^\s*\/\/\/?\s*(@ts-ignore)?)/; @@ -73853,9 +73566,9 @@ var ts; var diagnostic = diagnostics_2[_i]; var context = ""; if (diagnostic.file) { - var start = diagnostic.start, length_5 = diagnostic.length, file = 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_5), lastLine = _b.line, lastLineChar = _b.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 hasMoreThanFiveLines = (lastLine - firstLine) >= 4; @@ -74184,7 +73897,8 @@ var ts; dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker, getSourceFileFromReference: getSourceFileFromReference, sourceFileToPackageName: sourceFileToPackageName, - redirectTargetsSet: redirectTargetsSet + redirectTargetsSet: redirectTargetsSet, + isEmittedFile: isEmittedFile }; verifyCompilerOptions(); ts.performance.mark("afterProgram"); @@ -74594,24 +74308,26 @@ var ts; } function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers) { var declarationDiagnostics = []; - if (options.noEmit) { - return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; - } - // If the noEmitOnError flag is set, then check if we have any errors so far. If so, - // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we - // get any preEmit diagnostics, not just the ones - if (options.noEmitOnError) { - var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); - if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { - declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + if (!emitOnlyDtsFiles) { + if (options.noEmit) { + return { diagnostics: declarationDiagnostics, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true }; } - if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { - return { - diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), - sourceMaps: undefined, - emittedFiles: undefined, - emitSkipped: true - }; + // If the noEmitOnError flag is set, then check if we have any errors so far. If so, + // immediately bail out. Note that we pass 'undefined' for 'sourceFile' so that we + // get any preEmit diagnostics, not just the ones + if (options.noEmitOnError) { + var diagnostics = program.getOptionsDiagnostics(cancellationToken).concat(program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken)); + if (diagnostics.length === 0 && program.getCompilerOptions().declaration) { + declarationDiagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken); + } + if (diagnostics.length > 0 || declarationDiagnostics.length > 0) { + return { + diagnostics: ts.concatenate(diagnostics, declarationDiagnostics), + sourceMaps: undefined, + emittedFiles: undefined, + emitSkipped: true + }; + } } } // Create the emit resolver outside of the "emitTime" tracking code below. That way @@ -74622,7 +74338,7 @@ var ts; // This is because in the -out scenario all files need to be emitted, and therefore all // files need to be type checked. And the way to specify that all files need to be type // checked is to not pass the file to getEmitResolver. - var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile); + var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver((options.outFile || options.out) ? undefined : sourceFile, cancellationToken, emitOnlyDtsFiles); ts.performance.mark("beforeEmit"); var transformers = emitOnlyDtsFiles ? [] : ts.getTransformers(options, customTransformers); var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, emitOnlyDtsFiles, transformers); @@ -75175,7 +74891,7 @@ var ts; } }, shouldCreateNewSourceFile); if (packageId) { - var packageIdKey = packageId.name + "/" + packageId.subModuleName + "@" + packageId.version; + var packageIdKey = ts.packageIdToString(packageId); var fileFromPackageId = packageIdToSourceFile.get(packageIdKey); if (fileFromPackageId) { // Some other SourceFile already exists with this package name and version. @@ -75641,6 +75357,19 @@ var ts; hasEmitBlockingDiagnostics.set(toPath(emitFileName), true); programDiagnostics.add(diag); } + function isEmittedFile(file) { + if (options.noEmit) { + return false; + } + return ts.forEachEmittedFile(getEmitHost(), function (_a) { + var jsFilePath = _a.jsFilePath, declarationFilePath = _a.declarationFilePath; + return isSameFile(jsFilePath, file) || + (declarationFilePath && isSameFile(declarationFilePath, file)); + }); + } + function isSameFile(file1, file2) { + return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */; + } } ts.createProgram = createProgram; /* @internal */ @@ -75688,6 +75417,2168 @@ var ts; return res; } })(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers) { + var outputFiles = []; + var emitResult = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + return { outputFiles: outputFiles, emitSkipped: emitResult.emitSkipped }; + function writeFile(fileName, text, writeByteOrderMark) { + outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text }); + } + } + ts.getFileEmitOutput = getFileEmitOutput; +})(ts || (ts = {})); +/*@internal*/ +(function (ts) { + var BuilderState; + (function (BuilderState) { + /** + * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true + */ + function getReferencedFiles(program, sourceFile, getCanonicalFileName) { + var referencedFiles; + // We need to use a set here since the code can contain the same import twice, + // but that will only be one dependency. + // To avoid invernal conversion, the key of the referencedFiles map must be of type Path + if (sourceFile.imports && sourceFile.imports.length > 0) { + var checker = program.getTypeChecker(); + for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) { + var importName = _a[_i]; + var symbol = checker.getSymbolAtLocation(importName); + if (symbol && symbol.declarations && symbol.declarations[0]) { + var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]); + if (declarationSourceFile) { + addReferencedFile(declarationSourceFile.path); + } + } + } + } + var sourceFileDirectory = ts.getDirectoryPath(sourceFile.path); + // Handle triple slash references + if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) { + for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) { + var referencedFile = _c[_b]; + var referencedPath = ts.toPath(referencedFile.fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(referencedPath); + } + } + // Handle type reference directives + if (sourceFile.resolvedTypeReferenceDirectiveNames) { + sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) { + if (!resolvedTypeReferenceDirective) { + return; + } + var fileName = resolvedTypeReferenceDirective.resolvedFileName; + var typeFilePath = ts.toPath(fileName, sourceFileDirectory, getCanonicalFileName); + addReferencedFile(typeFilePath); + }); + } + return referencedFiles; + function addReferencedFile(referencedPath) { + if (!referencedFiles) { + referencedFiles = ts.createMap(); + } + referencedFiles.set(referencedPath, true); + } + } + /** + * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed + */ + function canReuseOldState(newReferencedMap, oldState) { + return oldState && !oldState.referencedMap === !newReferencedMap; + } + BuilderState.canReuseOldState = canReuseOldState; + /** + * Creates the state of file references and signature for the new program from oldState if it is safe + */ + function create(newProgram, getCanonicalFileName, oldState) { + var fileInfos = ts.createMap(); + var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? ts.createMap() : undefined; + var hasCalledUpdateShapeSignature = ts.createMap(); + var useOldState = canReuseOldState(referencedMap, oldState); + // Create the reference map, and set the file infos + for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + var version_1 = sourceFile.version; + var oldInfo = useOldState && oldState.fileInfos.get(sourceFile.path); + if (referencedMap) { + var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName); + if (newReferences) { + referencedMap.set(sourceFile.path, newReferences); + } + } + fileInfos.set(sourceFile.path, { version: version_1, signature: oldInfo && oldInfo.signature }); + } + return { + fileInfos: fileInfos, + referencedMap: referencedMap, + hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature, + allFilesExcludingDefaultLibraryFile: undefined, + allFileNames: undefined + }; + } + BuilderState.create = create; + /** + * Gets the files affected by the path from the program + */ + function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature) { + // Since the operation could be cancelled, the signatures are always stored in the cache + // They will be commited once it is safe to use them + // eg when calling this api from tsserver, if there is no cancellation of the operation + // In the other cases the affected files signatures are commited only after the iteration through the result is complete + var signatureCache = cacheToUpdateSignature || ts.createMap(); + var sourceFile = programOfThisState.getSourceFileByPath(path); + if (!sourceFile) { + return ts.emptyArray; + } + if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash)) { + return [sourceFile]; + } + var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash); + if (!cacheToUpdateSignature) { + // Commit all the signatures in the signature cache + updateSignaturesFromCache(state, signatureCache); + } + return result; + } + BuilderState.getFilesAffectedBy = getFilesAffectedBy; + /** + * Updates the signatures from the cache into state's fileinfo signatures + * This should be called whenever it is safe to commit the state of the builder + */ + function updateSignaturesFromCache(state, signatureCache) { + signatureCache.forEach(function (signature, path) { + state.fileInfos.get(path).signature = signature; + state.hasCalledUpdateShapeSignature.set(path, true); + }); + } + BuilderState.updateSignaturesFromCache = updateSignaturesFromCache; + /** + * Returns if the shape of the signature has changed since last emit + */ + function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash) { + ts.Debug.assert(!!sourceFile); + // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate + if (state.hasCalledUpdateShapeSignature.has(sourceFile.path) || cacheToUpdateSignature.has(sourceFile.path)) { + return false; + } + var info = state.fileInfos.get(sourceFile.path); + ts.Debug.assert(!!info); + var prevSignature = info.signature; + var latestSignature; + if (sourceFile.isDeclarationFile) { + latestSignature = sourceFile.version; + } + else { + var emitOutput = ts.getFileEmitOutput(programOfThisState, sourceFile, /*emitOnlyDtsFiles*/ true, cancellationToken); + if (emitOutput.outputFiles && emitOutput.outputFiles.length > 0) { + latestSignature = computeHash(emitOutput.outputFiles[0].text); + } + else { + latestSignature = prevSignature; + } + } + cacheToUpdateSignature.set(sourceFile.path, latestSignature); + return !prevSignature || latestSignature !== prevSignature; + } + /** + * Get all the dependencies of the sourceFile + */ + function getAllDependencies(state, programOfThisState, sourceFile) { + 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) { + return getAllFileNames(state, programOfThisState); + } + // If this is non module emit, or its a global file, it depends on all the source files + if (!state.referencedMap || (!ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile))) { + return getAllFileNames(state, programOfThisState); + } + // Get the references, traversing deep from the referenceMap + var seenMap = ts.createMap(); + var queue = [sourceFile.path]; + while (queue.length) { + var path = queue.pop(); + if (!seenMap.has(path)) { + seenMap.set(path, true); + 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) { + queue.push(value); + } + } + } + } + return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { + var file = programOfThisState.getSourceFileByPath(path); + return file ? file.fileName : path; + })); + var _b; + } + BuilderState.getAllDependencies = getAllDependencies; + /** + * Gets the names of all files from the program + */ + function getAllFileNames(state, programOfThisState) { + if (!state.allFileNames) { + var sourceFiles = programOfThisState.getSourceFiles(); + state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; }); + } + return state.allFileNames; + } + /** + * Gets the files referenced by the the file path + */ + function getReferencedByPaths(state, referencedFilePath) { + return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) { + var filePath = _a[0], referencesInFile = _a[1]; + return referencesInFile.has(referencedFilePath) ? filePath : undefined; + })); + } + /** + * For script files that contains only ambient external modules, although they are not actually external module files, + * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore, + * there are no point to rebuild all script files if these special files have changed. However, if any statement + * in the file is not ambient external module, we treat it as a regular script file. + */ + function containsOnlyAmbientModules(sourceFile) { + for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) { + var statement = _a[_i]; + if (!ts.isModuleWithStringLiteralName(statement)) { + return false; + } + } + return true; + } + /** + * Gets all files of the program excluding the default library file + */ + function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) { + // Use cached result + if (state.allFilesExcludingDefaultLibraryFile) { + return state.allFilesExcludingDefaultLibraryFile; + } + var result; + addSourceFile(firstSourceFile); + for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) { + var sourceFile = _a[_i]; + if (sourceFile !== firstSourceFile) { + addSourceFile(sourceFile); + } + } + state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray; + return state.allFilesExcludingDefaultLibraryFile; + function addSourceFile(sourceFile) { + if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) { + (result || (result = [])).push(sourceFile); + } + } + } + /** + * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) { + var compilerOptions = programOfThisState.getCompilerOptions(); + // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project, + // so returning the file itself is good enough. + if (compilerOptions && (compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + /** + * When program emits modular code, gets the files affected by the sourceFile whose shape has changed + */ + function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash) { + if (!ts.isExternalModule(sourceFileWithUpdatedShape) && !containsOnlyAmbientModules(sourceFileWithUpdatedShape)) { + return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape); + } + var compilerOptions = programOfThisState.getCompilerOptions(); + if (compilerOptions && (compilerOptions.isolatedModules || compilerOptions.out || compilerOptions.outFile)) { + return [sourceFileWithUpdatedShape]; + } + // Now we need to if each file in the referencedBy list has a shape change as well. + // Because if so, its own referencedBy files need to be saved as well to make the + // emitting result consistent with files on disk. + var seenFileNamesMap = ts.createMap(); + // Start with the paths this file was referenced by + seenFileNamesMap.set(sourceFileWithUpdatedShape.path, sourceFileWithUpdatedShape); + var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.path); + while (queue.length > 0) { + var currentPath = queue.pop(); + if (!seenFileNamesMap.has(currentPath)) { + var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath); + seenFileNamesMap.set(currentPath, currentSourceFile); + if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash)) { + queue.push.apply(queue, getReferencedByPaths(state, currentPath)); + } + } + } + // Return array of values that needs emit + // Return array of values that needs emit + return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; })); + } + })(BuilderState = ts.BuilderState || (ts.BuilderState = {})); +})(ts || (ts = {})); +/// +/*@internal*/ +var ts; +(function (ts) { + function hasSameKeys(map1, map2) { + if (map1 === undefined) { + return map2 === undefined; + } + if (map2 === undefined) { + return map1 === undefined; + } + // Has same size and every key is present in both maps + return map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); }); + } + /** + * Create the state so that we can iterate on changedFiles/affected files + */ + function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) { + var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState); + state.program = newProgram; + var compilerOptions = newProgram.getCompilerOptions(); + if (!compilerOptions.outFile && !compilerOptions.out) { + state.semanticDiagnosticsPerFile = ts.createMap(); + } + state.changedFilesSet = ts.createMap(); + var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState); + var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile; + if (useOldState) { + // Verify the sanity of old state + if (!oldState.currentChangedFilePath) { + ts.Debug.assert(!oldState.affectedFiles && (!oldState.currentAffectedFilesSignatures || !oldState.currentAffectedFilesSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated"); + } + if (canCopySemanticDiagnostics) { + ts.Debug.assert(!ts.forEachKey(oldState.changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files"); + } + // Copy old state's changed files set + ts.copyEntries(oldState.changedFilesSet, state.changedFilesSet); + } + // Update changed files and copy semantic diagnostics if we can + var referencedMap = state.referencedMap; + var oldReferencedMap = useOldState && oldState.referencedMap; + state.fileInfos.forEach(function (info, sourceFilePath) { + var oldInfo; + var newReferences; + // if not using old state, every file is changed + if (!useOldState || + // File wasnt present in old state + !(oldInfo = oldState.fileInfos.get(sourceFilePath)) || + // versions dont match + oldInfo.version !== info.version || + // Referenced files changed + !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) || + // Referenced file was deleted in the new program + newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) { + // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated + state.changedFilesSet.set(sourceFilePath, true); + } + else if (canCopySemanticDiagnostics) { + // Unchanged file copy diagnostics + var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath); + if (diagnostics) { + state.semanticDiagnosticsPerFile.set(sourceFilePath, diagnostics); + } + } + }); + return state; + } + /** + * Verifies that source file is ok to be used in calls that arent handled by next + */ + function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) { + ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.path)); + } + /** + * This function returns the next affected file to be processed. + * Note that until doneAffected is called it would keep reporting same result + * This is to allow the callers to be able to actually remove affected file only when the operation is complete + * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained + */ + function getNextAffectedFile(state, cancellationToken, computeHash) { + while (true) { + var affectedFiles = state.affectedFiles; + if (affectedFiles) { + var seenAffectedFiles = state.seenAffectedFiles, semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile; + var affectedFilesIndex = state.affectedFilesIndex; + while (affectedFilesIndex < affectedFiles.length) { + var affectedFile = affectedFiles[affectedFilesIndex]; + if (!seenAffectedFiles.has(affectedFile.path)) { + // Set the next affected file as seen and remove the cached semantic diagnostics + state.affectedFilesIndex = affectedFilesIndex; + semanticDiagnosticsPerFile.delete(affectedFile.path); + return affectedFile; + } + seenAffectedFiles.set(affectedFile.path, true); + affectedFilesIndex++; + } + // Remove the changed file from the change set + state.changedFilesSet.delete(state.currentChangedFilePath); + state.currentChangedFilePath = undefined; + // Commit the changes in file signature + ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures); + state.currentAffectedFilesSignatures.clear(); + state.affectedFiles = undefined; + } + // Get next changed file + var nextKey = state.changedFilesSet.keys().next(); + if (nextKey.done) { + // Done + return undefined; + } + // With --out or --outFile all outputs go into single file + // so operations are performed directly on program, return program + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + return state.program; + } + // Get next batch of affected files + state.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures || ts.createMap(); + state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, state.program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures); + state.currentChangedFilePath = nextKey.value; + state.semanticDiagnosticsPerFile.delete(nextKey.value); + state.affectedFilesIndex = 0; + state.seenAffectedFiles = state.seenAffectedFiles || ts.createMap(); + } + } + /** + * This is called after completing operation on the next affected file. + * The operations here are postponed to ensure that cancellation during the iteration is handled correctly + */ + function doneWithAffectedFile(state, affected) { + if (affected === state.program) { + state.changedFilesSet.clear(); + } + else { + state.seenAffectedFiles.set(affected.path, true); + state.affectedFilesIndex++; + } + } + /** + * Returns the result with affected file + */ + function toAffectedFileResult(state, result, affected) { + doneWithAffectedFile(state, affected); + return { result: result, affected: affected }; + } + /** + * Gets the semantic diagnostics either from cache if present, or otherwise from program and caches it + * Note that it is assumed that the when asked about semantic diagnostics, the file has been taken out of affected files/changed file set + */ + function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) { + var path = sourceFile.path; + var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path); + // Report the semantic diagnostics from the cache if we already have those diagnostics present + if (cachedDiagnostics) { + return cachedDiagnostics; + } + // Diagnostics werent cached, get them from program, and cache the result + var diagnostics = state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + state.semanticDiagnosticsPerFile.set(path, diagnostics); + return diagnostics; + } + var BuilderProgramKind; + (function (BuilderProgramKind) { + BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram"; + BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram"; + })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {})); + function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var host; + var newProgram; + if (ts.isArray(newProgramOrRootNames)) { + newProgram = ts.createProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram && oldProgram.getProgram()); + host = oldProgramOrHost; + } + else { + newProgram = newProgramOrRootNames; + host = hostOrOptions; + oldProgram = oldProgramOrHost; + } + return { host: host, newProgram: newProgram, oldProgram: oldProgram }; + } + ts.getBuilderCreationParameters = getBuilderCreationParameters; + function createBuilderProgram(kind, _a) { + var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram; + // Return same program if underlying program doesnt change + var oldState = oldProgram && oldProgram.getState(); + if (oldState && newProgram === oldState.program) { + newProgram = undefined; + oldState = undefined; + return oldProgram; + } + /** + * Create the canonical file name for identity + */ + var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + /** + * Computing hash to for signature verification + */ + var computeHash = host.createHash || ts.identity; + var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState); + // To ensure that we arent storing any references to old program or new program without state + newProgram = undefined; + oldProgram = undefined; + oldState = undefined; + var result = { + getState: function () { return state; }, + getProgram: function () { return state.program; }, + getCompilerOptions: function () { return state.program.getCompilerOptions(); }, + getSourceFile: function (fileName) { return state.program.getSourceFile(fileName); }, + getSourceFiles: function () { return state.program.getSourceFiles(); }, + getOptionsDiagnostics: function (cancellationToken) { return state.program.getOptionsDiagnostics(cancellationToken); }, + getGlobalDiagnostics: function (cancellationToken) { return state.program.getGlobalDiagnostics(cancellationToken); }, + getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return state.program.getSyntacticDiagnostics(sourceFile, cancellationToken); }, + getSemanticDiagnostics: getSemanticDiagnostics, + emit: emit, + getAllDependencies: function (sourceFile) { return ts.BuilderState.getAllDependencies(state, state.program, sourceFile); }, + getCurrentDirectory: function () { return state.program.getCurrentDirectory(); } + }; + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + result.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile; + } + else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + result.emitNextAffectedFile = emitNextAffectedFile; + } + else { + ts.notImplemented(); + } + return result; + /** + * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + return toAffectedFileResult(state, + // When whole program is affected, do emit only once (eg when --out or --outFile is specified) + // Otherwise just affected file + state.program.emit(affected === state.program ? undefined : affected, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), affected); + } + /** + * Emits the JavaScript and declaration files. + * When targetSource file is specified, emits the files corresponding to that source file, + * otherwise for the whole program. + * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified, + * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified, + * it will only emit all the affected files instead of whole program + * + * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host + * in that order would be used to write the files + */ + function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) { + assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile); + if (!targetSourceFile) { + // Emit and report any errors we ran into. + var sourceMaps = []; + var emitSkipped = void 0; + var diagnostics = void 0; + var emittedFiles = []; + var affectedEmitResult = void 0; + while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) { + emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped; + diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics); + emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles); + sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps); + } + return { + emitSkipped: emitSkipped, + diagnostics: diagnostics || ts.emptyArray, + emittedFiles: emittedFiles, + sourceMaps: sourceMaps + }; + } + } + return state.program.emit(targetSourceFile, writeFile || host.writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + } + /** + * Return the semantic diagnostics for the next affected file or undefined if iteration is complete + * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true + */ + function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) { + while (true) { + var affected = getNextAffectedFile(state, cancellationToken, computeHash); + if (!affected) { + // Done + return undefined; + } + else if (affected === state.program) { + // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified) + return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected); + } + // Get diagnostics for the affected file if its not ignored + if (ignoreSourceFile && ignoreSourceFile(affected)) { + // Get next affected file + doneWithAffectedFile(state, affected); + continue; + } + return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected); + } + } + /** + * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program + * The semantic diagnostics are cached and managed here + * Note that it is assumed that when asked about semantic diagnostics through this API, + * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics + * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided, + * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics + */ + function getSemanticDiagnostics(sourceFile, cancellationToken) { + assertSourceFileOkWithoutNextAffectedCall(state, sourceFile); + var compilerOptions = state.program.getCompilerOptions(); + if (compilerOptions.outFile || compilerOptions.out) { + ts.Debug.assert(!state.semanticDiagnosticsPerFile); + // We dont need to cache the diagnostics just return them from program + return state.program.getSemanticDiagnostics(sourceFile, cancellationToken); + } + if (sourceFile) { + return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken); + } + if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) { + // When semantic builder asks for diagnostics of the whole program, + // ensure that all the affected files are handled + var affected = void 0; + while (affected = getNextAffectedFile(state, cancellationToken, computeHash)) { + doneWithAffectedFile(state, affected); + } + } + 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)); + } + return diagnostics || ts.emptyArray; + } + } + ts.createBuilderProgram = createBuilderProgram; +})(ts || (ts = {})); +(function (ts) { + function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram; + function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram)); + } + ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram; + function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram) { + var program = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, oldProgram).newProgram; + return { + // Only return program, all other methods are not implemented + getProgram: function () { return program; }, + getState: ts.notImplemented, + getCompilerOptions: ts.notImplemented, + getSourceFile: ts.notImplemented, + getSourceFiles: ts.notImplemented, + getOptionsDiagnostics: ts.notImplemented, + getGlobalDiagnostics: ts.notImplemented, + getSyntacticDiagnostics: ts.notImplemented, + getSemanticDiagnostics: ts.notImplemented, + emit: ts.notImplemented, + getAllDependencies: ts.notImplemented, + getCurrentDirectory: ts.notImplemented + }; + } + ts.createAbstractBuilder = createAbstractBuilder; +})(ts || (ts = {})); +/// +/* @internal */ +var ts; +(function (ts) { + function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) { + if (!host.getDirectories || !host.readDirectory) { + return undefined; + } + var cachedReadDirectoryResult = ts.createMap(); + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + fileExists: fileExists, + readFile: function (path, encoding) { return host.readFile(path, encoding); }, + directoryExists: host.directoryExists && directoryExists, + getDirectories: getDirectories, + readDirectory: readDirectory, + createDirectory: host.createDirectory && createDirectory, + writeFile: host.writeFile && writeFile, + addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, + addOrDeleteFile: addOrDeleteFile, + clearCache: clearCache + }; + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function getCachedFileSystemEntries(rootDirPath) { + return cachedReadDirectoryResult.get(rootDirPath); + } + function getCachedFileSystemEntriesForBaseDir(path) { + return getCachedFileSystemEntries(ts.getDirectoryPath(path)); + } + function getBaseNameOfFileName(fileName) { + return ts.getBaseFileName(ts.normalizePath(fileName)); + } + function createCachedFileSystemEntries(rootDir, rootDirPath) { + var resultFromHost = { + files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [], + directories: host.getDirectories(rootDir) || [] + }; + cachedReadDirectoryResult.set(rootDirPath, resultFromHost); + return resultFromHost; + } + /** + * If the readDirectory result was already cached, it returns that + * Otherwise gets result from host and caches it. + * The host request is done under try catch block to avoid caching incorrect result + */ + function tryReadDirectory(rootDir, rootDirPath) { + var cachedResult = getCachedFileSystemEntries(rootDirPath); + if (cachedResult) { + return cachedResult; + } + try { + return createCachedFileSystemEntries(rootDir, rootDirPath); + } + 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)); + return undefined; + } + } + function fileNameEqual(name1, name2) { + return getCanonicalFileName(name1) === getCanonicalFileName(name2); + } + function hasEntry(entries, name) { + return ts.some(entries, function (file) { return fileNameEqual(file, name); }); + } + function updateFileSystemEntry(entries, baseName, isValid) { + if (hasEntry(entries, baseName)) { + if (!isValid) { + return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); + } + } + else if (isValid) { + return entries.push(baseName); + } + } + function writeFile(fileName, data, writeByteOrderMark) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + if (result) { + updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true); + } + return host.writeFile(fileName, data, writeByteOrderMark); + } + function fileExists(fileName) { + var path = toPath(fileName); + var result = getCachedFileSystemEntriesForBaseDir(path); + return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || + host.fileExists(fileName); + } + function directoryExists(dirPath) { + var path = toPath(dirPath); + return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); + } + function createDirectory(dirPath) { + var path = toPath(dirPath); + var result = getCachedFileSystemEntriesForBaseDir(path); + var baseFileName = getBaseNameOfFileName(dirPath); + if (result) { + updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true); + } + host.createDirectory(dirPath); + } + function getDirectories(rootDir) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return result.directories.slice(); + } + return host.getDirectories(rootDir); + } + function readDirectory(rootDir, extensions, excludes, includes, depth) { + var rootDirPath = toPath(rootDir); + var result = tryReadDirectory(rootDir, rootDirPath); + if (result) { + return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries); + } + return host.readDirectory(rootDir, extensions, excludes, includes, depth); + function getFileSystemEntries(dir) { + var path = toPath(dir); + if (path === rootDirPath) { + return result; + } + return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries; + } + } + function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { + var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); + if (existingResult) { + // Just clear the cache for now + // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated + clearCache(); + return undefined; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); + if (!parentResult) { + return undefined; + } + // This was earlier a file (hence not in cached directory contents) + // or we never cached the directory containing it + if (!host.directoryExists) { + // Since host doesnt support directory exists, clear the cache as otherwise it might not be same + clearCache(); + return undefined; + } + var baseName = getBaseNameOfFileName(fileOrDirectory); + var fsQueryResult = { + fileExists: host.fileExists(fileOrDirectoryPath), + directoryExists: host.directoryExists(fileOrDirectoryPath) + }; + if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { + // Folder added or removed, clear the cache instead of updating the folder and its structure + clearCache(); + } + else { + // No need to update the directory structure, just files + updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); + } + return fsQueryResult; + } + function addOrDeleteFile(fileName, filePath, eventKind) { + if (eventKind === ts.FileWatcherEventKind.Changed) { + return; + } + var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); + if (parentResult) { + updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); + } + } + function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { + updateFileSystemEntry(parentResult.files, baseName, fileExists); + } + function clearCache() { + cachedReadDirectoryResult.clear(); + } + } + ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + var ConfigFileProgramReloadLevel; + (function (ConfigFileProgramReloadLevel) { + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None"; + /** Update the file name list from the disk */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial"; + /** Reload completely by re-reading contents of config file from disk and updating program */ + ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full"; + })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {})); + /** + * Updates the existing missing file watches with the new set of missing files after new program is created + */ + function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) { + var missingFilePaths = program.getMissingFilePaths(); + var newMissingFilePathMap = ts.arrayToSet(missingFilePaths); + // Update the missing file paths watcher + ts.mutateMap(missingFileWatches, newMissingFilePathMap, { + // Watch the missing files + createNewValue: createMissingFileWatch, + // Files that are no longer missing (e.g. because they are no longer required) + // should no longer be watched. + onDeleteValue: closeFileWatcher + }); + } + ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch; + /** + * Updates the existing wild card directory watches with the new set of wild card directories from the config file + * after new program is created because the config file was reloaded or program was created first time from the config file + * Note that there is no need to call this function when the program is updated with additional files without reloading config files, + * as wildcard directories wont change unless reloading config file + */ + function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) { + ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, { + // Create new watch and recursive info + createNewValue: createWildcardDirectoryWatcher, + // Close existing watch thats not needed any more + onDeleteValue: closeFileWatcherOf, + // Close existing watch that doesnt match in the flags + onExistingValue: updateWildcardDirectoryWatcher + }); + function createWildcardDirectoryWatcher(directory, flags) { + // Create new watch and recursive info + return { + watcher: watchDirectory(directory, flags), + flags: flags + }; + } + function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) { + // Watcher needs to be updated if the recursive flags dont match + if (existingWatcher.flags === flags) { + return; + } + existingWatcher.watcher.close(); + existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags)); + } + } + ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories; + function isEmittedFileOfProgram(program, file) { + if (!program) { + return false; + } + return program.isEmittedFile(file); + } + ts.isEmittedFileOfProgram = isEmittedFileOfProgram; + function addFileWatcher(host, file, cb) { + return host.watchFile(file, cb); + } + ts.addFileWatcher = addFileWatcher; + function addFileWatcherWithLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb); + } + ts.addFileWatcherWithLogging = addFileWatcherWithLogging; + function addFileWatcherWithOnlyTriggerLogging(host, file, cb, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb); + } + ts.addFileWatcherWithOnlyTriggerLogging = addFileWatcherWithOnlyTriggerLogging; + function addFilePathWatcher(host, file, cb, path) { + return host.watchFile(file, function (fileName, eventKind) { return cb(fileName, eventKind, path); }); + } + ts.addFilePathWatcher = addFilePathWatcher; + function addFilePathWatcherWithLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, file, cb, path); + } + ts.addFilePathWatcherWithLogging = addFilePathWatcherWithLogging; + function addFilePathWatcherWithOnlyTriggerLogging(host, file, cb, path, log) { + var watcherCaption = "FileWatcher:: "; + return createWatcherWithLogging(addFileWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, file, cb, path); + } + ts.addFilePathWatcherWithOnlyTriggerLogging = addFilePathWatcherWithOnlyTriggerLogging; + function addDirectoryWatcher(host, directory, cb, flags) { + var recursive = (flags & 1 /* Recursive */) !== 0; + return host.watchDirectory(directory, cb, recursive); + } + ts.addDirectoryWatcher = addDirectoryWatcher; + function addDirectoryWatcherWithLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ false, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithLogging = addDirectoryWatcherWithLogging; + function addDirectoryWatcherWithOnlyTriggerLogging(host, directory, cb, flags, log) { + var watcherCaption = "DirectoryWatcher " + ((flags & 1 /* Recursive */) !== 0 ? "recursive" : "") + ":: "; + return createWatcherWithLogging(addDirectoryWatcher, watcherCaption, log, /*logOnlyTrigger*/ true, host, directory, cb, flags); + } + ts.addDirectoryWatcherWithOnlyTriggerLogging = addDirectoryWatcherWithOnlyTriggerLogging; + function createWatcherWithLogging(addWatch, watcherCaption, log, logOnlyTrigger, host, file, cb, optional) { + var info = "PathInfo: " + file; + if (!logOnlyTrigger) { + log(watcherCaption + "Added: " + info); + } + var watcher = addWatch(host, file, function (fileName, cbOptional1) { + var optionalInfo = cbOptional1 !== undefined ? " " + cbOptional1 : ""; + log(watcherCaption + "Trigger: " + fileName + optionalInfo + " " + info); + var start = ts.timestamp(); + cb(fileName, cbOptional1, optional); + var elapsed = ts.timestamp() - start; + log(watcherCaption + "Elapsed: " + elapsed + "ms Trigger: " + fileName + optionalInfo + " " + info); + }, optional); + return { + close: function () { + if (!logOnlyTrigger) { + log(watcherCaption + "Close: " + info); + } + watcher.close(); + } + }; + } + function closeFileWatcher(watcher) { + watcher.close(); + } + ts.closeFileWatcher = closeFileWatcher; + function closeFileWatcherOf(objWithWatcher) { + objWithWatcher.watcher.close(); + } + ts.closeFileWatcherOf = closeFileWatcherOf; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + ts.maxNumberOfFilesToIterateForInvalidation = 256; + function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) { + var filesWithChangedSetOfUnresolvedImports; + var filesWithInvalidatedResolutions; + var allFilesHaveInvalidatedResolution = false; + // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file. + // The key in the map is source file's path. + // The values are Map of resolutions with key being name lookedup. + var resolvedModuleNames = ts.createMap(); + var perDirectoryResolvedModuleNames = ts.createMap(); + var resolvedTypeReferenceDirectives = ts.createMap(); + var perDirectoryResolvedTypeReferenceDirectives = ts.createMap(); + var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); + var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost(); + /** + * These are the extensions that failed lookup files will have by default, + * any other extension of failed lookup will be store that path in custom failed lookup path + * This helps in not having to comb through all resolutions when files are added/removed + * Note that .d.ts file also has .d.ts extension hence will be part of default extensions + */ + var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */]; + var customFailedLookupPaths = ts.createMap(); + var directoryWatchesOfFailedLookups = ts.createMap(); + var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory())); + var rootPath = rootDir && resolutionHost.toPath(rootDir); + // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames + var typeRootsWatches = ts.createMap(); + return { + startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions, + finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions, + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + startCachingPerDirectoryResolution: clearPerDirectoryResolutions, + finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution, + resolveModuleNames: resolveModuleNames, + resolveTypeReferenceDirectives: resolveTypeReferenceDirectives, + removeResolutionsOfFile: removeResolutionsOfFile, + invalidateResolutionOfFile: invalidateResolutionOfFile, + createHasInvalidatedResolution: createHasInvalidatedResolution, + updateTypeRootsWatch: updateTypeRootsWatch, + closeTypeRootsWatch: closeTypeRootsWatch, + clear: clear + }; + function getResolvedModule(resolution) { + return resolution.resolvedModule; + } + function getResolvedTypeReferenceDirective(resolution) { + return resolution.resolvedTypeReferenceDirective; + } + function isInDirectoryPath(dir, file) { + if (dir === undefined || file.length <= dir.length) { + return false; + } + return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator; + } + function clear() { + ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf); + customFailedLookupPaths.clear(); + closeTypeRootsWatch(); + resolvedModuleNames.clear(); + resolvedTypeReferenceDirectives.clear(); + allFilesHaveInvalidatedResolution = false; + // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update + // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution) + clearPerDirectoryResolutions(); + } + function startRecordingFilesWithChangedResolutions() { + filesWithChangedSetOfUnresolvedImports = []; + } + function finishRecordingFilesWithChangedResolutions() { + var collected = filesWithChangedSetOfUnresolvedImports; + filesWithChangedSetOfUnresolvedImports = undefined; + return collected; + } + function createHasInvalidatedResolution(forceAllFilesAsInvalidated) { + if (allFilesHaveInvalidatedResolution || forceAllFilesAsInvalidated) { + // Any file asked would have invalidated resolution + filesWithInvalidatedResolutions = undefined; + return ts.returnTrue; + } + var collected = filesWithInvalidatedResolutions; + filesWithInvalidatedResolutions = undefined; + return function (path) { return collected && collected.has(path); }; + } + function clearPerDirectoryResolutions() { + perDirectoryResolvedModuleNames.clear(); + perDirectoryResolvedTypeReferenceDirectives.clear(); + } + function finishCachingPerDirectoryResolution() { + allFilesHaveInvalidatedResolution = false; + directoryWatchesOfFailedLookups.forEach(function (watcher, path) { + if (watcher.refCount === 0) { + directoryWatchesOfFailedLookups.delete(path); + watcher.watcher.close(); + } + }); + clearPerDirectoryResolutions(); + } + function resolveModuleName(moduleName, containingFile, compilerOptions, host) { + var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host); + // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts + if (!resolutionHost.getGlobalCache) { + return primaryResult; + } + // otherwise try to load typings from @types + var globalCache = resolutionHost.getGlobalCache(); + if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTypeScript(primaryResult.resolvedModule.extension))) { + // create different collection of failed lookup locations for second pass + // if it will fail and we've already found something during the first pass - we don't want to pollute its results + var _a = ts.loadModuleFromGlobalCache(moduleName, resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations; + if (resolvedModule) { + return { resolvedModule: resolvedModule, failedLookupLocations: ts.addRange(primaryResult.failedLookupLocations, failedLookupLocations) }; + } + } + // Default return the result from the first pass + return primaryResult; + } + function resolveNamesWithLocalCache(names, containingFile, cache, perDirectoryCache, loader, getResolutionWithResolvedFileName, reusedNames, logChanges) { + var path = resolutionHost.toPath(containingFile); + var resolutionsInFile = cache.get(path) || cache.set(path, ts.createMap()).get(path); + var dirPath = ts.getDirectoryPath(path); + var perDirectoryResolution = perDirectoryCache.get(dirPath); + if (!perDirectoryResolution) { + perDirectoryResolution = ts.createMap(); + perDirectoryCache.set(dirPath, perDirectoryResolution); + } + var resolvedModules = []; + var compilerOptions = resolutionHost.getCompilationSettings(); + var seenNamesInFile = ts.createMap(); + for (var _i = 0, names_2 = names; _i < names_2.length; _i++) { + var name = names_2[_i]; + var resolution = resolutionsInFile.get(name); + // Resolution is valid if it is present and not invalidated + if (!seenNamesInFile.has(name) && + allFilesHaveInvalidatedResolution || !resolution || resolution.isInvalidated) { + var existingResolution = resolution; + var resolutionInDirectory = perDirectoryResolution.get(name); + if (resolutionInDirectory) { + resolution = resolutionInDirectory; + } + else { + resolution = loader(name, containingFile, compilerOptions, resolutionHost); + perDirectoryResolution.set(name, resolution); + } + resolutionsInFile.set(name, resolution); + if (resolution.failedLookupLocations) { + if (existingResolution && existingResolution.failedLookupLocations) { + watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution); + } + else { + watchFailedLookupLocationOfResolution(resolution, 0); + } + } + else if (existingResolution) { + stopWatchFailedLookupLocationOfResolution(existingResolution); + } + if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) { + filesWithChangedSetOfUnresolvedImports.push(path); + // reset log changes to avoid recording the same file multiple times + logChanges = false; + } + } + ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated); + seenNamesInFile.set(name, true); + resolvedModules.push(getResolutionWithResolvedFileName(resolution)); + } + // Stop watching and remove the unused name + resolutionsInFile.forEach(function (resolution, name) { + if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) { + stopWatchFailedLookupLocationOfResolution(resolution); + resolutionsInFile.delete(name); + } + }); + return resolvedModules; + function resolutionIsEqualTo(oldResolution, newResolution) { + if (oldResolution === newResolution) { + return true; + } + if (!oldResolution || !newResolution || oldResolution.isInvalidated) { + return false; + } + var oldResult = getResolutionWithResolvedFileName(oldResolution); + var newResult = getResolutionWithResolvedFileName(newResolution); + if (oldResult === newResult) { + return true; + } + if (!oldResult || !newResult) { + return false; + } + return oldResult.resolvedFileName === newResult.resolvedFileName; + } + } + function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile) { + return resolveNamesWithLocalCache(typeDirectiveNames, containingFile, resolvedTypeReferenceDirectives, perDirectoryResolvedTypeReferenceDirectives, ts.resolveTypeReferenceDirective, getResolvedTypeReferenceDirective, + /*reusedNames*/ undefined, /*logChanges*/ false); + } + function resolveModuleNames(moduleNames, containingFile, reusedNames) { + return resolveNamesWithLocalCache(moduleNames, containingFile, resolvedModuleNames, perDirectoryResolvedModuleNames, resolveModuleName, getResolvedModule, reusedNames, logChangesWhenResolvingModule); + } + function isNodeModulesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules"); + } + function isNodeModulesAtTypesDirectory(dirPath) { + return ts.endsWith(dirPath, "/node_modules/@types"); + } + function isDirectoryAtleastAtLevelFromFSRoot(dirPath, minLevels) { + for (var searchIndex = ts.getRootLength(dirPath); minLevels > 0; minLevels--) { + searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1; + if (searchIndex === 0) { + // Folder isnt at expected minimun levels + return false; + } + } + return true; + } + function canWatchDirectory(dirPath) { + return isDirectoryAtleastAtLevelFromFSRoot(dirPath, + // When root is "/" do not watch directories like: + // "/", "/user", "/user/username", "/user/username/folderAtRoot" + // When root is "c:/" do not watch directories like: + // "c:/", "c:/folderAtRoot" + dirPath.charCodeAt(0) === 47 /* slash */ ? 3 : 1); + } + function filterFSRootDirectoriesToWatch(watchPath, dirPath) { + if (!canWatchDirectory(dirPath)) { + watchPath.ignore = true; + } + return watchPath; + } + function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) { + if (isInDirectoryPath(rootPath, failedLookupLocationPath)) { + return { dir: rootDir, dirPath: rootPath }; + } + var dir = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())); + var dirPath = ts.getDirectoryPath(failedLookupLocationPath); + // If directory path contains node module, get the most parent node_modules directory for watching + while (ts.stringContains(dirPath, "/node_modules/")) { + dir = ts.getDirectoryPath(dir); + dirPath = ts.getDirectoryPath(dirPath); + } + // If the directory is node_modules use it to watch + if (isNodeModulesDirectory(dirPath)) { + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, ts.getDirectoryPath(dirPath)); + } + // Use some ancestor of the root directory + if (rootPath !== undefined) { + while (!isInDirectoryPath(dirPath, rootPath)) { + var parentPath = ts.getDirectoryPath(dirPath); + if (parentPath === dirPath) { + break; + } + dirPath = parentPath; + dir = ts.getDirectoryPath(dir); + } + } + return filterFSRootDirectoriesToWatch({ dir: dir, dirPath: dirPath }, dirPath); + } + function isPathWithDefaultFailedLookupExtension(path) { + return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions); + } + function watchAndStopWatchDiffFailedLookupLocations(resolution, existingResolution) { + var failedLookupLocations = resolution.failedLookupLocations; + var existingFailedLookupLocations = existingResolution.failedLookupLocations; + for (var index = 0; index < failedLookupLocations.length; index++) { + if (index === existingFailedLookupLocations.length) { + // Additional failed lookup locations, watch from this index + watchFailedLookupLocationOfResolution(resolution, index); + return; + } + else if (failedLookupLocations[index] !== existingFailedLookupLocations[index]) { + // Different failed lookup locations, + // Watch new resolution failed lookup locations from this index and + // stop watching existing resolutions from this index + watchFailedLookupLocationOfResolution(resolution, index); + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, index); + return; + } + } + // All new failed lookup locations are already watched (and are same), + // Stop watching failed lookup locations of existing resolution after failed lookup locations length + stopWatchFailedLookupLocationOfResolutionFrom(existingResolution, failedLookupLocations.length); + } + function watchFailedLookupLocationOfResolution(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + // If the failed lookup location path is not one of the supported extensions, + // store it in the custom path + if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) { + var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0; + customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1); + } + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dir = _b.dir, dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + if (dirWatcher) { + dirWatcher.refCount++; + } + else { + directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath), refCount: 1 }); + } + } + } + } + function stopWatchFailedLookupLocationOfResolution(resolution) { + if (resolution.failedLookupLocations) { + stopWatchFailedLookupLocationOfResolutionFrom(resolution, 0); + } + } + function stopWatchFailedLookupLocationOfResolutionFrom(_a, startIndex) { + var failedLookupLocations = _a.failedLookupLocations; + for (var i = startIndex; i < failedLookupLocations.length; i++) { + var failedLookupLocation = failedLookupLocations[i]; + var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation); + var refCount = customFailedLookupPaths.get(failedLookupLocationPath); + if (refCount) { + if (refCount === 1) { + customFailedLookupPaths.delete(failedLookupLocationPath); + } + else { + ts.Debug.assert(refCount > 1); + customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1); + } + } + var _b = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath), dirPath = _b.dirPath, ignore = _b.ignore; + if (!ignore) { + var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath); + // Do not close the watcher yet since it might be needed by other failed lookup locations. + dirWatcher.refCount--; + } + } + } + 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 + 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) { + if (invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath)) { + resolutionHost.onInvalidatedResolution(); + } + } + }, 1 /* Recursive */); + } + function removeResolutionsOfFileFromCache(cache, filePath) { + // Deleted file, stop watching failed lookups for all the resolutions in the file + var resolutions = cache.get(filePath); + if (resolutions) { + resolutions.forEach(stopWatchFailedLookupLocationOfResolution); + cache.delete(filePath); + } + } + function removeResolutionsOfFile(filePath) { + removeResolutionsOfFileFromCache(resolvedModuleNames, filePath); + removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath); + } + function invalidateResolutionCache(cache, isInvalidatedResolution, getResolutionWithResolvedFileName) { + var seen = ts.createMap(); + cache.forEach(function (resolutions, containingFilePath) { + var dirPath = ts.getDirectoryPath(containingFilePath); + var seenInDir = seen.get(dirPath); + if (!seenInDir) { + seenInDir = ts.createMap(); + seen.set(dirPath, seenInDir); + } + resolutions.forEach(function (resolution, name) { + if (seenInDir.has(name)) { + return; + } + seenInDir.set(name, true); + if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { + // Mark the file as needing re-evaluation of module resolution instead of using it blindly. + resolution.isInvalidated = true; + (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + } + }); + }); + } + function hasReachedResolutionIterationLimit() { + var maxSize = resolutionHost.maxNumberOfFilesToIterateForInvalidation || ts.maxNumberOfFilesToIterateForInvalidation; + return resolvedModuleNames.size > maxSize || resolvedTypeReferenceDirectives.size > maxSize; + } + function invalidateResolutions(isInvalidatedResolution) { + // If more than maxNumberOfFilesToIterateForInvalidation present, + // just invalidated all files and recalculate the resolutions for files instead + if (hasReachedResolutionIterationLimit()) { + allFilesHaveInvalidatedResolution = true; + return; + } + invalidateResolutionCache(resolvedModuleNames, isInvalidatedResolution, getResolvedModule); + invalidateResolutionCache(resolvedTypeReferenceDirectives, isInvalidatedResolution, getResolvedTypeReferenceDirective); + } + function invalidateResolutionOfFile(filePath) { + removeResolutionsOfFile(filePath); + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + function (resolution, getResolutionWithResolvedFileName) { + var result = getResolutionWithResolvedFileName(resolution); + return result && resolutionHost.toPath(result.resolvedFileName) === filePath; + }); + } + function invalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) { + var isChangedFailedLookupLocation; + if (isCreatingWatchedDirectory) { + // Watching directory is created + // Invalidate any resolution has failed lookup in this directory + isChangedFailedLookupLocation = function (location) { return isInDirectoryPath(fileOrDirectoryPath, resolutionHost.toPath(location)); }; + } + else { + // Some file or directory in the watching directory is created + // Return early if it does not have any of the watching extension or not the custom failed lookup path + var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath); + if (isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || isNodeModulesDirectory(dirOfFileOrDirectory)) { + // Invalidate any resolution from this directory + isChangedFailedLookupLocation = function (location) { + var locationPath = resolutionHost.toPath(location); + return locationPath === fileOrDirectoryPath || ts.startsWith(resolutionHost.toPath(location), fileOrDirectoryPath); + }; + } + else { + if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) { + return false; + } + // Ignore emits from the program + if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) { + return false; + } + // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created + isChangedFailedLookupLocation = function (location) { return resolutionHost.toPath(location) === fileOrDirectoryPath; }; + } + } + var hasChangedFailedLookupLocation = function (resolution) { return ts.some(resolution.failedLookupLocations, isChangedFailedLookupLocation); }; + var invalidatedFilesCount = filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size; + invalidateResolutions( + // Resolution is invalidated if the resulting file name is same as the deleted file path + hasChangedFailedLookupLocation); + return allFilesHaveInvalidatedResolution || filesWithInvalidatedResolutions && filesWithInvalidatedResolutions.size !== invalidatedFilesCount; + } + function closeTypeRootsWatch() { + ts.clearMap(typeRootsWatches, ts.closeFileWatcher); + } + function createTypeRootsWatch(_typeRootPath, typeRoot) { + // Create new watch and recursive info + return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) { + var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory); + if (cachedDirectoryStructureHost) { + // Since the file existance changed, update the sourceFiles cache + cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + } + // For now just recompile + // We could potentially store more data here about whether it was/would be really be used or not + // and with that determine to trigger compilation but for now this is enough + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + }, 1 /* Recursive */); + } + /** + * Watches the types that would get added as part of getAutomaticTypeDirectiveNames + * To be called when compiler options change + */ + function updateTypeRootsWatch() { + var options = resolutionHost.getCompilationSettings(); + if (options.types) { + // No need to do any watch since resolution cache is going to handle the failed lookups + // for the types added by this + closeTypeRootsWatch(); + return; + } + // we need to assume the directories exist to ensure that we can get all the type root directories that get included + // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them + var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory }); + if (typeRoots) { + ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), { + createNewValue: createTypeRootsWatch, + onDeleteValue: ts.closeFileWatcher + }); + } + else { + closeTypeRootsWatch(); + } + } + /** + * Use this function to return if directory exists to get type roots to watch + * If we return directory exists then only the paths will be added to type roots + * Hence return true for all directories except root directories which are filtered from watching + */ + function directoryExistsForTypeRootWatch(nodeTypesDirectory) { + var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory)); + var dirPath = resolutionHost.toPath(dir); + return dirPath === rootPath || canWatchDirectory(dirPath); + } + } + ts.createResolutionCache = createResolutionCache; +})(ts || (ts = {})); +/// +/// +/// +/*@internal*/ +var ts; +(function (ts) { + var sysFormatDiagnosticsHost = ts.sys ? { + getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); }, + getNewLine: function () { return ts.sys.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames) + } : undefined; + /** + * Create a function that reports error by writing to the system and handles the formating of the diagnostic + */ + function createDiagnosticReporter(system, pretty) { + var host = system === ts.sys ? sysFormatDiagnosticsHost : { + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getNewLine: function () { return system.newLine; }, + getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames), + }; + if (!pretty) { + return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); }; + } + var diagnostics = new Array(1); + return function (diagnostic) { + diagnostics[0] = diagnostic; + system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine()); + diagnostics[0] = undefined; + }; + } + ts.createDiagnosticReporter = createDiagnosticReporter; + function clearScreenIfNotWatchingForFileChanges(system, diagnostic) { + if (system.clearScreen && diagnostic.code !== ts.Diagnostics.Compilation_complete_Watching_for_file_changes.code) { + system.clearScreen(); + } + } + /** + * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic + */ + function createWatchStatusReporter(system, pretty) { + return pretty ? + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = "[" + ts.formatColorAndReset(new Date().toLocaleTimeString(), ts.ForegroundColorEscapeSequences.Grey) + "] "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + } : + function (diagnostic, newLine) { + clearScreenIfNotWatchingForFileChanges(system, diagnostic); + var output = new Date().toLocaleTimeString() + " - "; + output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine + newLine); + system.write(output); + }; + } + ts.createWatchStatusReporter = createWatchStatusReporter; + /** Parses config file using System interface */ + function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { + var host = system; + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + var result = parseConfigFile(configFileName, optionsToExtend, host); + host.onConfigFileDiagnostic = undefined; + 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 parseConfigFile(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); + result.parseDiagnostics.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + var cwd = host.getCurrentDirectory(); + var configParseResult = ts.parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd)); + configParseResult.errors.forEach(function (diagnostic) { return host.onConfigFileDiagnostic(diagnostic); }); + return configParseResult; + } + ts.parseConfigFile = parseConfigFile; + /** + * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options + */ + function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName) { + // First get and report any syntactic errors. + var diagnostics = program.getSyntacticDiagnostics().slice(); + var reportSemanticDiagnostics = false; + // If we didn't have any syntactic errors, then also try getting the global and + // semantic errors. + if (diagnostics.length === 0) { + ts.addRange(diagnostics, program.getOptionsDiagnostics()); + ts.addRange(diagnostics, program.getGlobalDiagnostics()); + if (diagnostics.length === 0) { + reportSemanticDiagnostics = true; + } + } + // Emit and report any errors we ran into. + var _a = program.emit(), emittedFiles = _a.emittedFiles, emitSkipped = _a.emitSkipped, emitDiagnostics = _a.diagnostics; + ts.addRange(diagnostics, emitDiagnostics); + if (reportSemanticDiagnostics) { + ts.addRange(diagnostics, program.getSemanticDiagnostics()); + } + ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); + if (writeFileName) { + var currentDir_1 = program.getCurrentDirectory(); + ts.forEach(emittedFiles, function (file) { + var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1); + writeFileName("TSFILE: " + filepath); + }); + if (program.getCompilerOptions().listFiles) { + ts.forEach(program.getSourceFiles(), function (file) { + writeFileName(file.fileName); + }); + } + } + if (emitSkipped && diagnostics.length > 0) { + // If the emitter didn't emit anything, then pass that value along. + return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; + } + else if (diagnostics.length > 0) { + // The emitter emitted something, inform the caller if that happened in the presence + // of diagnostics or not. + return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated; + } + return ts.ExitStatus.Success; + } + ts.emitFilesAndReportErrors = emitFilesAndReportErrors; + var noopFileWatcher = { close: ts.noop }; + /** + * Creates the watch compiler host that can be extended with config file or root file names and options host + */ + function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) { + if (system === void 0) { system = ts.sys; } + if (!createProgram) { + createProgram = ts.createEmitAndSemanticDiagnosticsBuilderProgram; + } + var host = system; + var useCaseSensitiveFileNames = function () { return system.useCaseSensitiveFileNames; }; + var writeFileName = function (s) { return system.write(s + system.newLine); }; + return { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + getNewLine: function () { return system.newLine; }, + getCurrentDirectory: function () { return system.getCurrentDirectory(); }, + getDefaultLibLocation: getDefaultLibLocation, + getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); }, + fileExists: function (path) { return system.fileExists(path); }, + readFile: function (path, encoding) { return system.readFile(path, encoding); }, + directoryExists: function (path) { return system.directoryExists(path); }, + getDirectories: function (path) { return system.getDirectories(path); }, + readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); }, + realpath: system.realpath && (function (path) { return system.realpath(path); }), + getEnvironmentVariable: system.getEnvironmentVariable && (function (name) { return system.getEnvironmentVariable(name); }), + 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 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); }, + onWatchStatusChange: reportWatchStatus || createWatchStatusReporter(system), + createDirectory: function (path) { return system.createDirectory(path); }, + writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); }, + onCachedDirectoryStructureHostCreate: function (cacheHost) { return host = cacheHost || system; }, + createHash: system.createHash && (function (s) { return system.createHash(s); }), + createProgram: createProgram, + afterProgramCreate: emitFilesAndReportErrorUsingBuilder + }; + function getDefaultLibLocation() { + return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); + } + function emitFilesAndReportErrorUsingBuilder(builderProgram) { + emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName); + } + } + /** + * Report error and exit + */ + function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) { + reportDiagnostic(diagnostic); + system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + /** + * Creates the watch compiler host from system for config file in watch mode + */ + function createWatchCompilerHostOfConfigFile(configFileName, optionsToExtend, system, createProgram, reportDiagnostic, reportWatchStatus) { + reportDiagnostic = reportDiagnostic || createDiagnosticReporter(system); + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus); + host.onConfigFileDiagnostic = reportDiagnostic; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; + host.configFileName = configFileName; + host.optionsToExtend = optionsToExtend; + return host; + } + ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile; + /** + * Creates the watch compiler host from system for compiling root files and options in watch mode + */ + function createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus); + host.rootFiles = rootFiles; + host.options = options; + return host; + } + ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions; +})(ts || (ts = {})); +(function (ts) { + function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus) { + if (ts.isArray(rootFilesOrConfigFileName)) { + return ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + else { + return ts.createWatchCompilerHostOfConfigFile(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus); + } + } + ts.createWatchCompilerHost = createWatchCompilerHost; + function createWatchProgram(host) { + var builderProgram; + var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc + var missingFilesMap; // Map of file watchers for the missing files + var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file + var timerToUpdateProgram; // timer callback to recompile the program + var sourceFilesCache = ts.createMap(); // Cache that stores the source file and version info + var missingFilePathsRequestedForRelease; // These paths are held temparirly so that we can remove the entry from source file cache if the file is not tracked by missing files + var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations + var hasChangedAutomaticTypeDirectiveNames = false; // True if the automatic type directives have changed + var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames(); + var currentDirectory = host.getCurrentDirectory(); + var getCurrentDirectory = function () { return currentDirectory; }; + var readFile = function (path, encoding) { return host.readFile(path, encoding); }; + var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, createProgram = host.createProgram; + var rootFileNames = host.rootFiles, compilerOptions = host.options, configFileSpecs = host.configFileSpecs, configFileWildCardDirectories = host.configFileWildCardDirectories; + var cachedDirectoryStructureHost = configFileName && ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames); + if (cachedDirectoryStructureHost && host.onCachedDirectoryStructureHostCreate) { + host.onCachedDirectoryStructureHostCreate(cachedDirectoryStructureHost); + } + var directoryStructureHost = cachedDirectoryStructureHost || host; + var parseConfigFileHost = { + useCaseSensitiveFileNames: useCaseSensitiveFileNames, + readDirectory: function (path, extensions, exclude, include, depth) { return directoryStructureHost.readDirectory(path, extensions, exclude, include, depth); }, + fileExists: function (path) { return host.fileExists(path); }, + readFile: readFile, + getCurrentDirectory: getCurrentDirectory, + onConfigFileDiagnostic: host.onConfigFileDiagnostic, + onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic + }; + // From tsc we want to get already parsed result and hence check for rootFileNames + if (configFileName && !rootFileNames) { + parseConfigFile(); + } + var trace = host.trace && (function (s) { host.trace(s + newLine); }); + var loggingEnabled = trace && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); + var writeLog = loggingEnabled ? trace : ts.noop; + var watchFile = compilerOptions.extendedDiagnostics ? ts.addFileWatcherWithLogging : loggingEnabled ? ts.addFileWatcherWithOnlyTriggerLogging : ts.addFileWatcher; + var watchFilePath = compilerOptions.extendedDiagnostics ? ts.addFilePathWatcherWithLogging : ts.addFilePathWatcher; + var watchDirectoryWorker = compilerOptions.extendedDiagnostics ? ts.addDirectoryWatcherWithLogging : ts.addDirectoryWatcher; + if (configFileName) { + watchFile(host, configFileName, scheduleProgramReload, writeLog); + } + var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); + var newLine = updateNewLine(); + var compilerHost = { + // Members for CompilerHost + getSourceFile: function (fileName, languageVersion, onError, shouldCreateNewSourceFile) { return getVersionedSourceFileByPath(fileName, toPath(fileName), languageVersion, onError, shouldCreateNewSourceFile); }, + getSourceFileByPath: getVersionedSourceFileByPath, + getDefaultLibLocation: host.getDefaultLibLocation && (function () { return host.getDefaultLibLocation(); }), + getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, + writeFile: writeFile, + getCurrentDirectory: getCurrentDirectory, + useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; }, + getCanonicalFileName: getCanonicalFileName, + getNewLine: function () { return newLine; }, + fileExists: fileExists, + readFile: readFile, + trace: trace, + directoryExists: directoryStructureHost.directoryExists && (function (path) { return directoryStructureHost.directoryExists(path); }), + getDirectories: directoryStructureHost.getDirectories && (function (path) { return directoryStructureHost.getDirectories(path); }), + realpath: host.realpath && (function (s) { return host.realpath(s); }), + getEnvironmentVariable: host.getEnvironmentVariable ? (function (name) { return host.getEnvironmentVariable(name); }) : (function () { return ""; }), + onReleaseOldSourceFile: onReleaseOldSourceFile, + createHash: host.createHash && (function (data) { return host.createHash(data); }), + // Members for ResolutionCacheHost + toPath: toPath, + getCompilationSettings: function () { return compilerOptions; }, + watchDirectoryOfFailedLookupLocation: watchDirectory, + watchTypeRootsDirectory: watchDirectory, + getCachedDirectoryStructureHost: function () { return cachedDirectoryStructureHost; }, + onInvalidatedResolution: scheduleProgramUpdate, + onChangedAutomaticTypeDirectiveNames: function () { + hasChangedAutomaticTypeDirectiveNames = true; + scheduleProgramUpdate(); + }, + maxNumberOfFilesToIterateForInvalidation: host.maxNumberOfFilesToIterateForInvalidation, + getCurrentProgram: getCurrentProgram, + writeLog: writeLog + }; + // Cache for the module resolution + var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ? + ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) : + currentDirectory, + /*logChangesWhenResolvingModule*/ false); + // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names + compilerHost.resolveModuleNames = host.resolveModuleNames ? + (function (moduleNames, containingFile, reusedNames) { return host.resolveModuleNames(moduleNames, containingFile, reusedNames); }) : + (function (moduleNames, containingFile, reusedNames) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames); }); + compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ? + (function (typeDirectiveNames, containingFile) { return host.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }) : + (function (typeDirectiveNames, containingFile) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile); }); + var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives; + reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode); + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + return configFileName ? + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram } : + { getCurrentProgram: getCurrentBuilderProgram, getProgram: synchronizeProgram, updateRootFileNames: updateRootFileNames }; + function getCurrentBuilderProgram() { + return builderProgram; + } + function getCurrentProgram() { + return builderProgram && builderProgram.getProgram(); + } + function synchronizeProgram() { + writeLog("Synchronizing program"); + var program = getCurrentProgram(); + if (hasChangedCompilerOptions) { + newLine = updateNewLine(); + if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) { + resolutionCache.clear(); + } + } + // All resolutions are invalid if user provided resolutions + var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution); + if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames)) { + return builderProgram; + } + // Compile the program + var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !program; + hasChangedCompilerOptions = false; + resolutionCache.startCachingPerDirectoryResolution(); + compilerHost.hasInvalidatedResolution = hasInvalidatedResolution; + compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames; + builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram); + resolutionCache.finishCachingPerDirectoryResolution(); + // Update watches + ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = ts.createMap()), watchMissingFilePath); + if (needsUpdateInTypeRootWatch) { + resolutionCache.updateTypeRootsWatch(); + } + if (missingFilePathsRequestedForRelease) { + // These are the paths that program creater told us as not in use any more but were missing on the disk. + // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO, + // if there is already watcher for it (for missing files) + // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed + // so that at later time we have correct result of their presence + for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) { + var missingFilePath = missingFilePathsRequestedForRelease_1[_i]; + if (!missingFilesMap.has(missingFilePath)) { + sourceFilesCache.delete(missingFilePath); + } + } + missingFilePathsRequestedForRelease = undefined; + } + if (host.afterProgramCreate) { + host.afterProgramCreate(builderProgram); + } + reportWatchDiagnostic(ts.Diagnostics.Compilation_complete_Watching_for_file_changes); + return builderProgram; + } + function updateRootFileNames(files) { + ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode"); + rootFileNames = files; + scheduleProgramUpdate(); + } + function updateNewLine() { + return ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); }); + } + function toPath(fileName) { + return ts.toPath(fileName, currentDirectory, getCanonicalFileName); + } + function fileExists(fileName) { + var path = toPath(fileName); + var hostSourceFileInfo = sourceFilesCache.get(path); + if (hostSourceFileInfo !== undefined) { + return !ts.isString(hostSourceFileInfo); + } + return directoryStructureHost.fileExists(fileName); + } + function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) { + var hostSourceFile = sourceFilesCache.get(path); + // No source file on the host + if (ts.isString(hostSourceFile)) { + return undefined; + } + // Create new source file if requested or the versions dont match + if (!hostSourceFile || shouldCreateNewSourceFile || hostSourceFile.version.toString() !== hostSourceFile.sourceFile.version) { + var sourceFile = getNewSourceFile(); + if (hostSourceFile) { + if (shouldCreateNewSourceFile) { + hostSourceFile.version++; + } + if (sourceFile) { + hostSourceFile.sourceFile = sourceFile; + sourceFile.version = hostSourceFile.version.toString(); + if (!hostSourceFile.fileWatcher) { + hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + } + } + else { + // There is no source file on host any more, close the watch, missing file paths will track it + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, hostSourceFile.version.toString()); + } + } + else { + var fileWatcher = void 0; + if (sourceFile) { + sourceFile.version = "1"; + fileWatcher = watchFilePath(host, fileName, onSourceFileChange, path, writeLog); + sourceFilesCache.set(path, { sourceFile: sourceFile, version: 1, fileWatcher: fileWatcher }); + } + else { + sourceFilesCache.set(path, "0"); + } + } + return sourceFile; + } + return hostSourceFile.sourceFile; + function getNewSourceFile() { + var text; + try { + ts.performance.mark("beforeIORead"); + text = host.readFile(fileName, compilerOptions.charset); + ts.performance.mark("afterIORead"); + ts.performance.measure("I/O Read", "beforeIORead", "afterIORead"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined; + } + } + function removeSourceFile(path) { + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile !== undefined) { + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + resolutionCache.invalidateResolutionOfFile(path); + } + sourceFilesCache.delete(path); + } + } + function getSourceVersion(path) { + var hostSourceFile = sourceFilesCache.get(path); + return !hostSourceFile || ts.isString(hostSourceFile) ? undefined : hostSourceFile.version.toString(); + } + function onReleaseOldSourceFile(oldSourceFile, _oldOptions) { + var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.path); + // If this is the source file thats in the cache and new program doesnt need it, + // remove the cached entry. + // Note we arent deleting entry if file became missing in new program or + // there was version update and new source file was created. + if (hostSourceFileInfo) { + // record the missing file paths so they can be removed later if watchers arent tracking them + if (ts.isString(hostSourceFileInfo)) { + (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path); + } + else if (hostSourceFileInfo.sourceFile === oldSourceFile) { + sourceFilesCache.delete(oldSourceFile.path); + resolutionCache.removeResolutionsOfFile(oldSourceFile.path); + } + } + } + function reportWatchDiagnostic(message) { + if (host.onWatchStatusChange) { + host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine); + } + } + // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch + // operations (such as saving all modified files in an editor) a chance to complete before we kick + // off a new compilation. + function scheduleProgramUpdate() { + if (!host.setTimeout || !host.clearTimeout) { + return; + } + if (timerToUpdateProgram) { + host.clearTimeout(timerToUpdateProgram); + } + timerToUpdateProgram = host.setTimeout(updateProgram, 250); + } + function scheduleProgramReload() { + ts.Debug.assert(!!configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.Full; + scheduleProgramUpdate(); + } + function updateProgram() { + timerToUpdateProgram = undefined; + reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation); + switch (reloadLevel) { + case ts.ConfigFileProgramReloadLevel.Partial: + return reloadFileNamesFromConfigFile(); + case ts.ConfigFileProgramReloadLevel.Full: + return reloadConfigFile(); + default: + synchronizeProgram(); + return; + } + } + function reloadFileNamesFromConfigFile() { + var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getDirectoryPath(configFileName), compilerOptions, parseConfigFileHost); + if (!configFileSpecs.filesSpecs && result.fileNames.length === 0) { + host.onConfigFileDiagnostic(ts.getErrorForNoInputFiles(configFileSpecs, configFileName)); + } + rootFileNames = result.fileNames; + // Update the program + synchronizeProgram(); + } + function reloadConfigFile() { + writeLog("Reloading config file: " + configFileName); + reloadLevel = ts.ConfigFileProgramReloadLevel.None; + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.clearCache(); + } + parseConfigFile(); + hasChangedCompilerOptions = true; + synchronizeProgram(); + // Update the wild card directory watch + watchConfigFileWildCardDirectories(); + } + function parseConfigFile() { + var configParseResult = ts.parseConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost); + rootFileNames = configParseResult.fileNames; + compilerOptions = configParseResult.options; + configFileSpecs = configParseResult.configFileSpecs; + configFileWildCardDirectories = configParseResult.wildcardDirectories; + } + function onSourceFileChange(fileName, eventKind, path) { + updateCachedSystemWithFile(fileName, path, eventKind); + var hostSourceFile = sourceFilesCache.get(path); + if (hostSourceFile) { + // Update the cache + if (eventKind === ts.FileWatcherEventKind.Deleted) { + resolutionCache.invalidateResolutionOfFile(path); + if (!ts.isString(hostSourceFile)) { + hostSourceFile.fileWatcher.close(); + sourceFilesCache.set(path, (++hostSourceFile.version).toString()); + } + } + else { + // Deleted file created + if (ts.isString(hostSourceFile)) { + sourceFilesCache.delete(path); + } + else { + // file changed - just update the version + hostSourceFile.version++; + } + } + } + // Update the program + scheduleProgramUpdate(); + } + function updateCachedSystemWithFile(fileName, path, eventKind) { + if (cachedDirectoryStructureHost) { + cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind); + } + } + function watchDirectory(directory, cb, flags) { + return watchDirectoryWorker(host, directory, cb, flags, writeLog); + } + function watchMissingFilePath(missingFilePath) { + return watchFilePath(host, missingFilePath, onMissingFileChange, missingFilePath, writeLog); + } + function onMissingFileChange(fileName, eventKind, missingFilePath) { + updateCachedSystemWithFile(fileName, missingFilePath, eventKind); + if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) { + missingFilesMap.get(missingFilePath).close(); + missingFilesMap.delete(missingFilePath); + // Delete the entry in the source files cache so that new source file is created + removeSourceFile(missingFilePath); + // When a missing file is created, we should update the graph. + scheduleProgramUpdate(); + } + } + function watchConfigFileWildCardDirectories() { + if (configFileWildCardDirectories) { + ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = ts.createMap()), ts.createMapFromTemplate(configFileWildCardDirectories), watchWildcardDirectory); + } + else if (watchedWildcardDirectories) { + ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); + } + } + function watchWildcardDirectory(directory, flags) { + return watchDirectory(directory, function (fileOrDirectory) { + ts.Debug.assert(!!configFileName); + var fileOrDirectoryPath = toPath(fileOrDirectory); + // Since the file existance changed, update the sourceFiles cache + var result = cachedDirectoryStructureHost && cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath); + // Instead of deleting the file, mark it as changed instead + // Many times node calls add/remove/file when watching directories recursively + var hostSourceFile = sourceFilesCache.get(fileOrDirectoryPath); + if (hostSourceFile && !ts.isString(hostSourceFile) && (result ? result.fileExists : directoryStructureHost.fileExists(fileOrDirectory))) { + hostSourceFile.version++; + } + else { + removeSourceFile(fileOrDirectoryPath); + } + // If the the added or created file or directory is not supported file name, ignore the file + // But when watched directory is added/removed, we need to reload the file list + if (fileOrDirectoryPath !== directory && ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, compilerOptions)) { + writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory); + return; + } + // Reload is pending, do the reload + if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) { + reloadLevel = ts.ConfigFileProgramReloadLevel.Partial; + // Schedule Update the program + scheduleProgramUpdate(); + } + }, flags); + } + function ensureDirectoriesExist(directoryPath) { + if (directoryPath.length > ts.getRootLength(directoryPath) && !host.directoryExists(directoryPath)) { + var parentDirectory = ts.getDirectoryPath(directoryPath); + ensureDirectoriesExist(parentDirectory); + host.createDirectory(directoryPath); + } + } + function writeFile(fileName, text, writeByteOrderMark, onError) { + try { + ts.performance.mark("beforeIOWrite"); + ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(fileName))); + host.writeFile(fileName, text, writeByteOrderMark); + ts.performance.mark("afterIOWrite"); + ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite"); + } + catch (e) { + if (onError) { + onError(e.message); + } + } + } + } + ts.createWatchProgram = createWatchProgram; +})(ts || (ts = {})); /// /// /// @@ -75840,7 +77731,7 @@ var ts; }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -78711,8 +80602,8 @@ var ts; } } ts.findPrecedingToken = findPrecedingToken; - function isInString(sourceFile, position) { - var previousToken = findPrecedingToken(position, sourceFile); + function isInString(sourceFile, position, previousToken) { + if (previousToken === void 0) { previousToken = findPrecedingToken(position, sourceFile); } if (previousToken && ts.isStringTextContainingNode(previousToken)) { var start = previousToken.getStart(); var end = previousToken.getEnd(); @@ -78965,6 +80856,18 @@ var ts; return true; } ts.addToSeen = addToSeen; + function getSnapshotText(snap) { + return snap.getText(0, snap.getLength()); + } + ts.getSnapshotText = getSnapshotText; + function repeatString(str, count) { + var result = ""; + for (var i = 0; i < count; i++) { + result += str; + } + return result; + } + ts.repeatString = repeatString; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -78979,6 +80882,7 @@ var ts; var lineStart; var indent; resetWriter(); + var unknownWrite = function (text) { return writeKind(text, ts.SymbolDisplayPartKind.text); }; return { displayParts: function () { return displayParts; }, writeKeyword: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.keyword); }, @@ -78988,8 +80892,18 @@ var ts; writeStringLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeParameter: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.parameterName); }, writeProperty: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.propertyName); }, + writeLiteral: function (text) { return writeKind(text, ts.SymbolDisplayPartKind.stringLiteral); }, writeSymbol: writeSymbol, writeLine: writeLine, + write: unknownWrite, + writeTextOfNode: unknownWrite, + getText: function () { return ""; }, + getTextPos: function () { return 0; }, + getColumn: function () { return 0; }, + getLine: function () { return 0; }, + isAtStartOfLine: function () { return false; }, + rawWrite: ts.notImplemented, + getIndent: function () { return indent; }, increaseIndent: function () { indent++; }, decreaseIndent: function () { indent--; }, clear: resetWriter, @@ -79110,14 +81024,17 @@ var ts; /** * The default is CRLF. */ - function getNewLineOrDefaultFromHost(host) { - return host.getNewLine ? host.getNewLine() : carriageReturnLineFeed; + function getNewLineOrDefaultFromHost(host, formatSettings) { + return (formatSettings && formatSettings.newLineCharacter) || + (host.getNewLine && host.getNewLine()) || + carriageReturnLineFeed; } ts.getNewLineOrDefaultFromHost = getNewLineOrDefaultFromHost; function lineBreakPart() { return displayPart("\n", ts.SymbolDisplayPartKind.lineBreak); } ts.lineBreakPart = lineBreakPart; + /* @internal */ function mapToDisplayParts(writeDisplayParts) { try { writeDisplayParts(displayPartWriter); @@ -79130,20 +81047,20 @@ var ts; ts.mapToDisplayParts = mapToDisplayParts; function typeToDisplayParts(typechecker, type, enclosingDeclaration, flags) { return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration, flags); + typechecker.writeType(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, writer); }); } ts.typeToDisplayParts = typeToDisplayParts; function symbolToDisplayParts(typeChecker, symbol, enclosingDeclaration, meaning, flags) { return mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildSymbolDisplay(symbol, writer, enclosingDeclaration, meaning, flags); + typeChecker.writeSymbol(symbol, enclosingDeclaration, meaning, flags, writer); }); } ts.symbolToDisplayParts = symbolToDisplayParts; function signatureToDisplayParts(typechecker, signature, enclosingDeclaration, flags) { - flags |= 65536 /* UseAliasDefinedOutsideCurrentScope */; + flags |= 16384 /* UseAliasDefinedOutsideCurrentScope */ | 1024 /* MultilineObjectLiterals */ | 32 /* WriteTypeArgumentsOfSignature */ | 8192 /* OmitParameterModifiers */; return mapToDisplayParts(function (writer) { - typechecker.getSymbolDisplayBuilder().buildSignatureDisplay(signature, writer, enclosingDeclaration, flags); + typechecker.writeSignature(signature, enclosingDeclaration, flags, /*signatureKind*/ undefined, writer); }); } ts.signatureToDisplayParts = signatureToDisplayParts; @@ -79504,7 +81421,7 @@ var ts; var lastEnd = 0; for (var i = 0; i < dense.length; i += 3) { var start = dense[i]; - var length_6 = dense[i + 1]; + var length_5 = dense[i + 1]; var type = dense[i + 2]; // Make a whitespace entry between the last item and this one. if (lastEnd >= 0) { @@ -79513,8 +81430,8 @@ var ts; entries.push({ length: whitespaceLength_1, classification: ts.TokenClass.Whitespace }); } } - entries.push({ length: length_6, classification: convertClassification(type) }); - lastEnd = start + length_6; + entries.push({ length: length_5, classification: convertClassification(type) }); + lastEnd = start + length_5; } var whitespaceLength = text.length - lastEnd; if (whitespaceLength > 0) { @@ -79837,32 +81754,39 @@ var ts; if (!ts.isTrivia(kind)) { return start; } - // Don't bother with newlines/whitespace. - if (kind === 4 /* NewLineTrivia */ || kind === 5 /* WhitespaceTrivia */) { - continue; - } - // Only bother with the trivia if it at least intersects the span of interest. - if (ts.isComment(kind)) { - classifyComment(token, kind, start, width); - // Classifying a comment might cause us to reuse the trivia scanner - // (because of jsdoc comments). So after we classify the comment make - // sure we set the scanner position back to where it needs to be. - triviaScanner.setTextPos(end); - continue; - } - if (kind === 7 /* ConflictMarkerTrivia */) { - var text = sourceFile.text; - var ch = text.charCodeAt(start); - // for the <<<<<<< and >>>>>>> markers, we just add them in as comments - // in the classification stream. - if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { - pushClassification(start, width, 1 /* comment */); + switch (kind) { + case 4 /* NewLineTrivia */: + case 5 /* WhitespaceTrivia */: + // Don't bother with newlines/whitespace. continue; - } - // for the ||||||| and ======== markers, add a comment for the first line, - // and then lex all subsequent lines up until the end of the conflict marker. - ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); - classifyDisabledMergeCode(text, start, end); + case 2 /* SingleLineCommentTrivia */: + case 3 /* MultiLineCommentTrivia */: + // Only bother with the trivia if it at least intersects the span of interest. + classifyComment(token, kind, start, width); + // Classifying a comment might cause us to reuse the trivia scanner + // (because of jsdoc comments). So after we classify the comment make + // sure we set the scanner position back to where it needs to be. + triviaScanner.setTextPos(end); + continue; + case 7 /* ConflictMarkerTrivia */: + var text = sourceFile.text; + var ch = text.charCodeAt(start); + // for the <<<<<<< and >>>>>>> markers, we just add them in as comments + // in the classification stream. + if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) { + pushClassification(start, width, 1 /* comment */); + continue; + } + // for the ||||||| and ======== markers, add a comment for the first line, + // and then lex all subsequent lines up until the end of the conflict marker. + ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */); + classifyDisabledMergeCode(text, start, end); + break; + case 6 /* ShebangTrivia */: + // TODO: Maybe we should classify these. + break; + default: + ts.Debug.assertNever(kind); } } } @@ -80403,10 +82327,12 @@ var ts; function getCompletionEntriesFromTypings(host, options, scriptPath, span, result) { if (result === void 0) { result = []; } // Check for typings specified in compiler options + var seen = ts.createMap(); if (options.types) { for (var _i = 0, _a = options.types; _i < _a.length; _i++) { - var moduleName = _a[_i]; - result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + var typesName = _a[_i]; + var moduleName = ts.getUnmangledNameForScopedPackage(typesName); + pushResult(moduleName); } } else if (host.getDirectories) { @@ -80418,31 +82344,38 @@ var ts; if (typeRoots) { for (var _c = 0, typeRoots_2 = typeRoots; _c < typeRoots_2.length; _c++) { var root = typeRoots_2[_c]; - getCompletionEntriesFromDirectories(host, root, span, result); + getCompletionEntriesFromDirectories(root); } } - } - if (host.getDirectories) { // Also get all @types typings installed in visible node_modules directories for (var _d = 0, _e = findPackageJsons(scriptPath, host); _d < _e.length; _d++) { var packageJson = _e[_d]; var typesDir = ts.combinePaths(ts.getDirectoryPath(packageJson), "node_modules/@types"); - getCompletionEntriesFromDirectories(host, typesDir, span, result); + getCompletionEntriesFromDirectories(typesDir); } } return result; - } - function getCompletionEntriesFromDirectories(host, directory, span, result) { - if (host.getDirectories && tryDirectoryExists(host, directory)) { - var directories = tryGetDirectories(host, directory); - if (directories) { - for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { - var typeDirectory = directories_2[_i]; - typeDirectory = ts.normalizePath(typeDirectory); - result.push(createCompletionEntryForModule(ts.getBaseFileName(typeDirectory), "external module name" /* externalModuleName */, span)); + function getCompletionEntriesFromDirectories(directory) { + ts.Debug.assert(!!host.getDirectories); + if (tryDirectoryExists(host, directory)) { + var directories = tryGetDirectories(host, directory); + if (directories) { + for (var _i = 0, directories_2 = directories; _i < directories_2.length; _i++) { + var typeDirectory = directories_2[_i]; + typeDirectory = ts.normalizePath(typeDirectory); + var directoryName = ts.getBaseFileName(typeDirectory); + var moduleName = ts.getUnmangledNameForScopedPackage(directoryName); + pushResult(moduleName); + } } } } + function pushResult(moduleName) { + if (!seen.has(moduleName)) { + result.push(createCompletionEntryForModule(moduleName, "external module name" /* externalModuleName */, span)); + seen.set(moduleName, true); + } + } } function findPackageJsons(directory, host) { var paths = []; @@ -80580,16 +82513,19 @@ var ts; KeywordCompletionFilters[KeywordCompletionFilters["None"] = 0] = "None"; KeywordCompletionFilters[KeywordCompletionFilters["ClassElementKeywords"] = 1] = "ClassElementKeywords"; KeywordCompletionFilters[KeywordCompletionFilters["ConstructorParameterKeywords"] = 2] = "ConstructorParameterKeywords"; + KeywordCompletionFilters[KeywordCompletionFilters["FunctionLikeBodyKeywords"] = 3] = "FunctionLikeBodyKeywords"; // Keywords at function like body })(KeywordCompletionFilters || (KeywordCompletionFilters = {})); function getCompletionsAtPosition(host, typeChecker, log, compilerOptions, sourceFile, position, allSourceFiles, options) { if (ts.isInReferenceComment(sourceFile, position)) { var entries = Completions.PathCompletions.getTripleSlashReferenceCompletion(sourceFile, position, compilerOptions, host); return entries && pathCompletionsInfo(entries); } - if (ts.isInString(sourceFile, position)) { - return getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log); - } var contextToken = ts.findPrecedingToken(position, sourceFile); + if (ts.isInString(sourceFile, position, contextToken)) { + return !contextToken || !ts.isStringLiteral(contextToken) && !ts.isNoSubstitutionTemplateLiteral(contextToken) + ? undefined + : getStringLiteralCompletionEntries(sourceFile, contextToken, position, typeChecker, compilerOptions, host, log); + } if (contextToken && ts.isBreakOrContinueStatement(contextToken.parent) && (contextToken.kind === 72 /* BreakKeyword */ || contextToken.kind === 77 /* ContinueKeyword */ || contextToken.kind === 71 /* Identifier */)) { return getLabelCompletionAtPosition(contextToken.parent); @@ -80688,10 +82624,19 @@ var ts; return undefined; } var name = info.name, needsConvertPropertyAccess = info.needsConvertPropertyAccess; - ts.Debug.assert(!(needsConvertPropertyAccess && !propertyAccessToConvert)); if (needsConvertPropertyAccess && !includeInsertTextCompletions) { return undefined; } + var insertText; + var replacementSpan; + if (kind === 1 /* Global */ && origin && origin.type === "this-type") { + insertText = needsConvertPropertyAccess ? "this[\"" + name + "\"]" : "this." + name; + } + else if (needsConvertPropertyAccess) { + // TODO: GH#20619 Use configured quote style + insertText = "[\"" + name + "\"]"; + replacementSpan = ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end); + } // TODO(drosen): Right now we just permit *all* semantic meanings when calling // 'getSymbolKind' which is permissible given that it is backwards compatible; but // really we should consider passing the meaning for the node so that we don't report @@ -80705,13 +82650,10 @@ var ts; kindModifiers: ts.SymbolDisplay.getSymbolModifiers(symbol), sortText: "0", source: getSourceFromOrigin(origin), - // TODO: GH#20619 Use configured quote style - insertText: needsConvertPropertyAccess ? "[\"" + name + "\"]" : undefined, - replacementSpan: needsConvertPropertyAccess - ? ts.createTextSpanFromBounds(ts.findChildOfKind(propertyAccessToConvert, 23 /* DotToken */, sourceFile).getStart(sourceFile), propertyAccessToConvert.name.end) - : undefined, - hasAction: trueOrUndefined(needsConvertPropertyAccess || origin !== undefined), + hasAction: trueOrUndefined(!!origin && origin.type === "export"), isRecommended: trueOrUndefined(isRecommendedCompletionMatch(symbol, recommendedCompletion, typeChecker)), + insertText: insertText, + replacementSpan: replacementSpan, }; } function isRecommendedCompletionMatch(localSymbol, recommendedCompletion, checker) { @@ -80722,7 +82664,7 @@ var ts; return b ? true : undefined; } function getSourceFromOrigin(origin) { - return origin && ts.stripQuotes(origin.moduleSymbol.name); + return origin && origin.type === "export" ? ts.stripQuotes(origin.moduleSymbol.name) : undefined; } function getCompletionEntriesFromSymbols(symbols, entries, location, sourceFile, typeChecker, target, log, kind, includeInsertTextCompletions, propertyAccessToConvert, recommendedCompletion, symbolToOriginInfoMap) { var start = ts.timestamp(); @@ -80757,68 +82699,81 @@ var ts; return { isGlobalCompletion: false, isMemberCompletion: false, isNewIdentifierLocation: false, entries: entries }; } } - function getStringLiteralCompletionEntries(sourceFile, position, typeChecker, compilerOptions, host, log) { - var node = ts.findPrecedingToken(position, sourceFile); - if (!node || !ts.isStringLiteral(node) && !ts.isNoSubstitutionTemplateLiteral(node)) { - return undefined; - } - if (node.parent.kind === 265 /* PropertyAssignment */ && - node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && - node.parent.name === node) { - // Get quoted name of properties of the object literal expression - // i.e. interface ConfigFiles { - // 'jspm:dev': string - // } - // let files: ConfigFiles = { - // '/*completion position*/' - // } - // - // function foo(c: ConfigFiles) {} - // foo({ - // '/*completion position*/' - // }); - return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); - } - else if (ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node) { - // Get all names of properties on the expression - // i.e. interface A { - // 'prop1': string - // } - // let a: A; - // a['/*completion position*/'] - var type = typeChecker.getTypeAtLocation(node.parent.expression); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); - } - else if (node.parent.kind === 239 /* ImportDeclaration */ || node.parent.kind === 245 /* ExportDeclaration */ - || ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) || ts.isImportCall(node.parent) - || ts.isExpressionOfExternalModuleImportEqualsDeclaration(node)) { - // Get all known external module names or complete a path to a module - // i.e. import * as ns from "/*completion position*/"; - // var y = import("/*completion position*/"); - // import x = require("/*completion position*/"); - // var y = require("/*completion position*/"); - // export * from "/*completion position*/"; - var entries = Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker); - return pathCompletionsInfo(entries); - } - else if (ts.isIndexedAccessTypeNode(node.parent.parent)) { - // Get all apparent property names - // i.e. interface Foo { - // foo: string; - // bar: string; - // } - // let x: Foo["/*completion position*/"] - var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); - return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); - } - else { - var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); - if (argumentInfo) { - // Get string literal completions from specialized signatures of the target - // i.e. declare function f(a: 'A'); - // f("/*completion position*/") - return getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker); + function getStringLiteralCompletionEntries(sourceFile, node, position, typeChecker, compilerOptions, host, log) { + switch (node.parent.kind) { + case 174 /* LiteralType */: + switch (node.parent.parent.kind) { + case 160 /* TypeReference */: + // TODO: GH#21168 + return undefined; + case 172 /* IndexedAccessType */: + // Get all apparent property names + // i.e. interface Foo { + // foo: string; + // bar: string; + // } + // let x: Foo["/*completion position*/"] + var type = typeChecker.getTypeFromTypeNode(node.parent.parent.objectType); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + default: + return undefined; + } + case 265 /* PropertyAssignment */: + if (node.parent.parent.kind === 179 /* ObjectLiteralExpression */ && + node.parent.name === node) { + // Get quoted name of properties of the object literal expression + // i.e. interface ConfigFiles { + // 'jspm:dev': string + // } + // let files: ConfigFiles = { + // '/*completion position*/' + // } + // + // function foo(c: ConfigFiles) {} + // foo({ + // '/*completion position*/' + // }); + return getStringLiteralCompletionEntriesFromPropertyAssignment(node.parent, sourceFile, typeChecker, compilerOptions.target, log); + } + return fromContextualType(); + case 181 /* ElementAccessExpression */: { + var _a = node.parent, expression = _a.expression, argumentExpression = _a.argumentExpression; + if (node === argumentExpression) { + // Get all names of properties on the expression + // i.e. interface A { + // 'prop1': string + // } + // let a: A; + // a['/*completion position*/'] + var type = typeChecker.getTypeAtLocation(expression); + return getStringLiteralCompletionEntriesFromElementAccessOrIndexedAccess(node, sourceFile, type, typeChecker, compilerOptions.target, log); + } + break; } + case 182 /* CallExpression */: + case 183 /* NewExpression */: + if (!ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteral*/ false) && !ts.isImportCall(node.parent)) { + var argumentInfo = ts.SignatureHelp.getImmediatelyContainingArgumentInfo(node, position, sourceFile); + // Get string literal completions from specialized signatures of the target + // i.e. declare function f(a: 'A'); + // f("/*completion position*/") + return argumentInfo ? getStringLiteralCompletionEntriesFromCallExpression(argumentInfo, typeChecker) : fromContextualType(); + } + // falls through + case 239 /* ImportDeclaration */: + case 245 /* ExportDeclaration */: + case 249 /* ExternalModuleReference */: + // Get all known external module names or complete a path to a module + // i.e. import * as ns from "/*completion position*/"; + // var y = import("/*completion position*/"); + // import x = require("/*completion position*/"); + // var y = require("/*completion position*/"); + // export * from "/*completion position*/"; + return pathCompletionsInfo(Completions.PathCompletions.getStringLiteralCompletionsFromModuleNames(sourceFile, node, compilerOptions, host, typeChecker)); + default: + return fromContextualType(); + } + function fromContextualType() { // Get completion for string literal from string literal type // i.e. var x: "hi" | "hello" = "/*completion position*/" return getStringLiteralCompletionEntriesFromType(getContextualTypeFromParent(node, typeChecker), typeChecker); @@ -80951,7 +82906,7 @@ var ts; }) || { type: "none" }; } function getSymbolName(symbol, origin, target) { - return origin && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ + return origin && origin.type === "export" && origin.isDefaultExport && symbol.escapedName === "default" /* Default */ // Name of "export default foo;" is "foo". Name of "export default 0" is the filename converted to camelCase. ? ts.firstDefined(symbol.declarations, function (d) { return ts.isExportAssignment(d) && ts.isIdentifier(d.expression) ? d.expression.text : undefined; }) || ts.codefix.moduleSymbolToValidIdentifier(origin.moduleSymbol, target) @@ -81004,7 +82959,7 @@ var ts; Completions.getCompletionEntryDetails = getCompletionEntryDetails; function getCompletionEntryCodeActionsAndSourceDisplay(symbolToOriginInfoMap, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) { var symbolOriginInfo = symbolToOriginInfoMap[ts.getSymbolId(symbol)]; - return symbolOriginInfo + return symbolOriginInfo && symbolOriginInfo.type === "export" ? getCodeActionsAndSourceDisplayForImport(symbolOriginInfo, symbol, program, checker, host, compilerOptions, sourceFile, previousToken, formatContext, getCanonicalFileName, allSourceFiles) : { codeActions: undefined, sourceDisplay: undefined }; } @@ -81018,7 +82973,6 @@ var ts; host: host, program: program, checker: checker, - newLineCharacter: host.getNewLine(), compilerOptions: compilerOptions, sourceFile: sourceFile, formatContext: formatContext, @@ -81389,6 +83343,9 @@ var ts; keywordFilters = 2 /* ConstructorParameterKeywords */; return true; } + if (tryGetFunctionLikeBodyCompletionContainer(contextToken)) { + keywordFilters = 3 /* FunctionLikeBodyKeywords */; + } if (classLikeContainer = tryGetClassLikeCompletionContainer(contextToken)) { // cursor inside class declaration getGetClassLikeCompletionSymbols(classLikeContainer); @@ -81447,6 +83404,17 @@ var ts; } var symbolMeanings = 793064 /* Type */ | 107455 /* Value */ | 1920 /* Namespace */ | 2097152 /* Alias */; symbols = typeChecker.getSymbolsInScope(scopeNode, symbolMeanings); + // Need to insert 'this.' before properties of `this` type, so only do that if `includeInsertTextCompletions` + if (options.includeInsertTextCompletions && scopeNode.kind !== 269 /* SourceFile */) { + var thisType = typeChecker.tryGetThisTypeAt(scopeNode); + if (thisType) { + for (var _i = 0, _a = getPropertiesForCompletion(thisType, typeChecker, /*isForAccess*/ true); _i < _a.length; _i++) { + var symbol = _a[_i]; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { type: "this-type" }; + symbols.push(symbol); + } + } + } if (options.includeExternalModuleExports) { getSymbolsFromOtherSourceFileExports(symbols, previousToken && ts.isIdentifier(previousToken) ? previousToken.text : "", target); } @@ -81534,7 +83502,7 @@ var ts; // Don't add a completion for a re-export, only for the original. // If `symbol.parent !== ...`, this comes from an `export * from "foo"` re-export. Those don't create new symbols. // If `some(...)`, this comes from an `export { foo } from "foo"` re-export, which creates a new symbol (thus isn't caught by the first check). - if (symbol.parent !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) + if (typeChecker.getMergedSymbol(symbol.parent) !== typeChecker.resolveExternalModuleSymbol(moduleSymbol) || ts.some(symbol.declarations, function (d) { return ts.isExportSpecifier(d) && !!d.parent.parent.moduleSpecifier; })) { continue; } @@ -81542,10 +83510,10 @@ var ts; if (isDefaultExport) { symbol = ts.getLocalSymbolForExportDefault(symbol) || symbol; } - var origin = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + var origin = { type: "export", moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; if (stringContainsCharactersInOrder(getSymbolName(symbol, origin, target).toLowerCase(), tokenTextLowerCase)) { symbols.push(symbol); - symbolToOriginInfoMap[ts.getSymbolId(symbol)] = { moduleSymbol: moduleSymbol, isDefaultExport: isDefaultExport }; + symbolToOriginInfoMap[ts.getSymbolId(symbol)] = origin; } } }); @@ -81924,6 +83892,21 @@ var ts; } return undefined; } + function tryGetFunctionLikeBodyCompletionContainer(contextToken) { + if (contextToken) { + var prev_1; + var container = ts.findAncestor(contextToken.parent, function (node) { + if (ts.isClassLike(node)) { + return "quit"; + } + if (ts.isFunctionLikeDeclaration(node) && prev_1 === node.body) { + return true; + } + prev_1 = node; + }); + return container && container; + } + } function tryGetContainingJsxElement(contextToken) { if (contextToken) { var parent = contextToken.parent; @@ -82270,13 +84253,13 @@ var ts; return validIdentiferResult; switch (kind) { case 5 /* None */: - case 1 /* Global */: case 3 /* MemberLike */: return undefined; case 0 /* ObjectPropertyDeclaration */: // TODO: GH#18169 return { name: JSON.stringify(name), needsConvertPropertyAccess: false }; case 2 /* PropertyAccess */: + case 1 /* Global */: // Don't add a completion for a name starting with a space. See https://github.com/Microsoft/TypeScript/pull/20547 return name.charCodeAt(0) === 32 /* space */ ? undefined : { name: name, needsConvertPropertyAccess: true }; case 4 /* String */: @@ -82301,6 +84284,8 @@ var ts; return getFilteredKeywordCompletions(isClassMemberCompletionKeywordText); case 2 /* ConstructorParameterKeywords */: return getFilteredKeywordCompletions(isConstructorParameterCompletionKeywordText); + case 3 /* FunctionLikeBodyKeywords */: + return getFilteredKeywordCompletions(isFunctionLikeBodyCompletionKeywordText); default: ts.Debug.assertNever(keywordFilter); } @@ -82354,6 +84339,24 @@ var ts; function isConstructorParameterCompletionKeywordText(text) { return isConstructorParameterCompletionKeyword(ts.stringToToken(text)); } + function isFunctionLikeBodyCompletionKeyword(kind) { + switch (kind) { + case 114 /* PublicKeyword */: + case 112 /* PrivateKeyword */: + case 113 /* ProtectedKeyword */: + case 131 /* ReadonlyKeyword */: + case 123 /* ConstructorKeyword */: + case 115 /* StaticKeyword */: + case 117 /* AbstractKeyword */: + case 125 /* GetKeyword */: + case 135 /* SetKeyword */: + return false; + } + return true; + } + function isFunctionLikeBodyCompletionKeywordText(text) { + return isFunctionLikeBodyCompletionKeyword(ts.stringToToken(text)); + } function isEqualityOperatorKind(kind) { switch (kind) { case 34 /* EqualsEqualsEqualsToken */: @@ -83859,7 +85862,7 @@ var ts; } /** Core find-all-references algorithm for a normal symbol. */ function getReferencedSymbolsForSymbol(symbol, node, sourceFiles, checker, cancellationToken, options) { - symbol = skipPastExportOrImportSpecifier(symbol, node, checker); + symbol = skipPastExportOrImportSpecifierOrUnion(symbol, node, checker); // Compute the meaning from the location and the symbol it references var searchMeaning = getIntersectingMeaningFromDeclarations(ts.getMeaningFromLocation(node), symbol.declarations); var result = []; @@ -83902,7 +85905,7 @@ var ts; } } /** Handle a few special cases relating to export/import specifiers. */ - function skipPastExportOrImportSpecifier(symbol, node, checker) { + function skipPastExportOrImportSpecifierOrUnion(symbol, node, checker) { var parent = node.parent; if (ts.isExportSpecifier(parent)) { return getLocalSymbolForExportSpecifier(node, symbol, parent, checker); @@ -83911,7 +85914,12 @@ var ts; // We're at `foo` in `import { foo as bar }`. Probably intended to find all refs on the original, not just on the import. return checker.getImmediateAliasedSymbol(symbol); } - return symbol; + // If the symbol is declared as part of a declaration like `{ type: "a" } | { type: "b" }`, use the property on the union type to get more references. + return ts.firstDefined(symbol.declarations, function (decl) { + return ts.isTypeLiteralNode(decl.parent) && ts.isUnionTypeNode(decl.parent.parent) + ? checker.getPropertyOfType(checker.getTypeFromTypeNode(decl.parent.parent), symbol.name) + : undefined; + }) || symbol; } var SpecialSearchKind; (function (SpecialSearchKind) { @@ -83925,8 +85933,8 @@ var ts; */ var State = /** @class */ (function () { function State(sourceFiles, - /** True if we're searching for constructor references. */ - specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { + /** True if we're searching for constructor references. */ + specialSearchKind, checker, cancellationToken, searchMeaning, options, result) { this.sourceFiles = sourceFiles; this.specialSearchKind = specialSearchKind; this.checker = checker; @@ -85240,26 +87248,14 @@ var ts; return undefined; } var symbol = typeChecker.getSymbolAtLocation(node); - if (!symbol) { - return undefined; - } - var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node); + var type = symbol && typeChecker.getTypeOfSymbolAtLocation(symbol, node); if (!type) { return undefined; } if (type.flags & 131072 /* Union */ && !(type.flags & 16 /* Enum */)) { - var result_5 = []; - ts.forEach(type.types, function (t) { - if (t.symbol) { - ts.addRange(/*to*/ result_5, /*from*/ getDefinitionFromSymbol(typeChecker, t.symbol, node)); - } - }); - return result_5; + return ts.flatMap(type.types, function (t) { return t.symbol && getDefinitionFromSymbol(typeChecker, t.symbol, node); }); } - if (!type.symbol) { - return undefined; - } - return getDefinitionFromSymbol(typeChecker, type.symbol, node); + return type.symbol && getDefinitionFromSymbol(typeChecker, type.symbol, node); } GoToDefinition.getTypeDefinitionAtPosition = getTypeDefinitionAtPosition; function getDefinitionAndBoundSpan(program, sourceFile, position) { @@ -85303,59 +87299,29 @@ var ts; } } function getDefinitionFromSymbol(typeChecker, symbol, node) { - var result = []; - var declarations = symbol.getDeclarations(); var _a = getSymbolInfo(typeChecker, symbol, node), symbolName = _a.symbolName, symbolKind = _a.symbolKind, containerName = _a.containerName; - if (!tryAddConstructSignature(symbol, node, symbolKind, symbolName, containerName, result) && - !tryAddCallSignature(symbol, node, symbolKind, symbolName, containerName, result)) { - // Just add all the declarations. - ts.forEach(declarations, function (declaration) { - result.push(createDefinitionInfo(declaration, symbolKind, symbolName, containerName)); - }); - } - return result; - function tryAddConstructSignature(symbol, location, symbolKind, symbolName, containerName, result) { + return getConstructSignatureDefinition() || getCallSignatureDefinition() || ts.map(symbol.declarations, function (declaration) { return createDefinitionInfo(declaration, symbolKind, symbolName, containerName); }); + function getConstructSignatureDefinition() { // Applicable only if we are in a new expression, or we are on a constructor declaration // and in either case the symbol has a construct signature definition, i.e. class - if (ts.isNewExpressionTarget(location) || location.kind === 123 /* ConstructorKeyword */) { - if (symbol.flags & 32 /* Class */) { - // Find the first class-like declaration and try to get the construct signature. - for (var _i = 0, _a = symbol.getDeclarations(); _i < _a.length; _i++) { - var declaration = _a[_i]; - if (ts.isClassLike(declaration)) { - return tryAddSignature(declaration.members, /*selectConstructors*/ true, symbolKind, symbolName, containerName, result); - } - } - ts.Debug.fail("Expected declaration to have at least one class-like declaration"); - } + if (ts.isNewExpressionTarget(node) || node.kind === 123 /* ConstructorKeyword */ && symbol.flags & 32 /* Class */) { + var cls = ts.find(symbol.declarations, ts.isClassLike) || ts.Debug.fail("Expected declaration to have at least one class-like declaration"); + return getSignatureDefinition(cls.members, /*selectConstructors*/ true); } - return false; } - function tryAddCallSignature(symbol, location, symbolKind, symbolName, containerName, result) { - if (ts.isCallExpressionTarget(location) || ts.isNewExpressionTarget(location) || ts.isNameOfFunctionDeclaration(location)) { - return tryAddSignature(symbol.declarations, /*selectConstructors*/ false, symbolKind, symbolName, containerName, result); - } - return false; + function getCallSignatureDefinition() { + return ts.isCallExpressionTarget(node) || ts.isNewExpressionTarget(node) || ts.isNameOfFunctionDeclaration(node) + ? getSignatureDefinition(symbol.declarations, /*selectConstructors*/ false) + : undefined; } - function tryAddSignature(signatureDeclarations, selectConstructors, symbolKind, symbolName, containerName, result) { + function getSignatureDefinition(signatureDeclarations, selectConstructors) { if (!signatureDeclarations) { - return false; + return undefined; } - var declarations = []; - var definition; - for (var _i = 0, signatureDeclarations_1 = signatureDeclarations; _i < signatureDeclarations_1.length; _i++) { - var d = signatureDeclarations_1[_i]; - if (selectConstructors ? d.kind === 153 /* Constructor */ : isSignatureDeclaration(d)) { - declarations.push(d); - if (d.body) - definition = d; - } - } - if (declarations.length) { - result.push(createDefinitionInfo(definition || ts.lastOrUndefined(declarations), symbolKind, symbolName, containerName)); - return true; - } - return false; + var declarations = signatureDeclarations.filter(selectConstructors ? ts.isConstructorDeclaration : isSignatureDeclaration); + return declarations.length + ? [createDefinitionInfo(ts.find(declarations, function (d) { return !!d.body; }) || ts.last(declarations), symbolKind, symbolName, containerName)] + : undefined; } } function isSignatureDeclaration(node) { @@ -85497,18 +87463,29 @@ var ts; // from Array - Array and Array var documentationComment = []; forEachUnique(declarations, function (declaration) { - ts.forEach(ts.getAllJSDocs(declaration), function (doc) { - if (doc.comment) { - if (documentationComment.length) { - documentationComment.push(ts.lineBreakPart()); - } - documentationComment.push(ts.textPart(doc.comment)); + for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { + var comment = _a[_i].comment; + if (comment === undefined) + continue; + if (documentationComment.length) { + documentationComment.push(ts.lineBreakPart()); } - }); + documentationComment.push(ts.textPart(comment)); + } }); return documentationComment; } JsDoc.getJsDocCommentsFromDeclarations = getJsDocCommentsFromDeclarations; + function getCommentHavingNodes(declaration) { + switch (declaration.kind) { + case 289 /* JSDocPropertyTag */: + return [declaration]; + case 288 /* JSDocTypedefTag */: + return [declaration.parent]; + default: + return ts.getJSDocCommentsAndTags(declaration); + } + } function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; @@ -85539,10 +87516,13 @@ var ts; return comment; } function withNode(node) { - return node.getText() + " " + comment; + return addComment(node.getText()); } function withList(list) { - return list.map(function (x) { return x.getText(); }) + " " + comment; + return addComment(list.map(function (x) { return x.getText(); }).join(", ")); + } + function addComment(s) { + return comment === undefined ? s : s + " " + comment; } } /** @@ -85955,8 +87935,8 @@ var ts; if (baseFileName !== "package.json" && baseFileName !== "bower.json") { continue; } - var result_6 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); - var packageJson = result_6.config; + var result_5 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); }); + var packageJson = result_5.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. @@ -88321,6 +90301,7 @@ var ts; var callTarget = ts.getInvokedExpression(invocation); var callTargetSymbol = typeChecker.getSymbolAtLocation(callTarget); var callTargetDisplayParts = callTargetSymbol && ts.symbolToDisplayParts(typeChecker, callTargetSymbol, /*enclosingDeclaration*/ undefined, /*meaning*/ undefined); + var printer = ts.createPrinter({ removeComments: true }); var items = ts.map(candidates, function (candidateSignature) { var signatureHelpParameters; var prefixDisplayParts = []; @@ -88336,14 +90317,20 @@ var ts; signatureHelpParameters = typeParameters && typeParameters.length > 0 ? ts.map(typeParameters, createSignatureHelpParameterForTypeParameter) : ts.emptyArray; suffixDisplayParts.push(ts.punctuationPart(29 /* GreaterThanToken */)); var parameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForParametersAndDelimiters(candidateSignature.thisParameter, candidateSignature.parameters, writer, invocation); + var flags = 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */; + var thisParameter = candidateSignature.thisParameter ? [typeChecker.symbolToParameterDeclaration(candidateSignature.thisParameter, invocation, flags)] : []; + var params = ts.createNodeArray(thisParameter.concat(ts.map(candidateSignature.parameters, function (param) { return typeChecker.symbolToParameterDeclaration(param, invocation, flags); }))); + printer.writeList(1296 /* CallExpressionArguments */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); ts.addRange(suffixDisplayParts, parameterParts); } else { isVariadic = candidateSignature.hasRestParameter; var typeParameterParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildDisplayForTypeParametersAndDelimiters(candidateSignature.typeParameters, writer, invocation); + if (candidateSignature.typeParameters && candidateSignature.typeParameters.length) { + var args = ts.createNodeArray(ts.map(candidateSignature.typeParameters, function (p) { return typeChecker.typeParameterToDeclaration(p, invocation); })); + printer.writeList(26896 /* TypeParameters */, args, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); + } }); ts.addRange(prefixDisplayParts, typeParameterParts); prefixDisplayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -88351,7 +90338,15 @@ var ts; suffixDisplayParts.push(ts.punctuationPart(20 /* CloseParenToken */)); } var returnTypeParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildReturnTypeDisplay(candidateSignature, writer, invocation); + writer.writePunctuation(":"); + writer.writeSpace(" "); + var predicate = typeChecker.getTypePredicateOfSignature(candidateSignature); + if (predicate) { + typeChecker.writeTypePredicate(predicate, invocation, /*flags*/ undefined, writer); + } + else { + typeChecker.writeType(typeChecker.getReturnTypeOfSignature(candidateSignature), invocation, /*flags*/ undefined, writer); + } }); ts.addRange(suffixDisplayParts, returnTypeParts); return { @@ -88372,7 +90367,8 @@ var ts; return { items: items, applicableSpan: applicableSpan, selectedItemIndex: selectedItemIndex, argumentIndex: argumentIndex, argumentCount: argumentCount }; function createSignatureHelpParameterForParameter(parameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildParameterDisplay(parameter, writer, invocation); + var param = typeChecker.symbolToParameterDeclaration(parameter, invocation, 8192 /* OmitParameterModifiers */ | 3112960 /* IgnoreErrors */); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: parameter.name, @@ -88383,7 +90379,8 @@ var ts; } function createSignatureHelpParameterForTypeParameter(typeParameter) { var displayParts = ts.mapToDisplayParts(function (writer) { - return typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(typeParameter, writer, invocation); + var param = typeChecker.typeParameterToDeclaration(typeParameter, invocation); + printer.writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(invocation)), writer); }); return { name: typeParameter.symbol.name, @@ -88518,6 +90515,7 @@ var ts; var hasAddedSymbolInfo; var isThisExpression = location.kind === 99 /* ThisKeyword */ && ts.isExpression(location); var type; + var printer; var documentationFromAlias; // Class at constructor site need to be shown as constructor apart from property,method, vars if (symbolKind !== "" /* unknown */ || symbolFlags & 32 /* Class */ || symbolFlags & 2097152 /* Alias */) { @@ -88586,14 +90584,14 @@ var ts; displayParts.push(ts.punctuationPart(56 /* ColonToken */)); displayParts.push(ts.spacePart()); if (!(type.flags & 65536 /* Object */ && type.objectFlags & 16 /* Anonymous */) && type.symbol) { - ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */)); + ts.addRange(displayParts, ts.symbolToDisplayParts(typeChecker, type.symbol, enclosingDeclaration, /*meaning*/ undefined, 4 /* AllowAnyNodeKind */ | 1 /* WriteTypeParametersOrArguments */)); displayParts.push(ts.lineBreakPart()); } if (useConstructSignatures) { displayParts.push(ts.keywordPart(94 /* NewKeyword */)); displayParts.push(ts.spacePart()); } - addSignatureDisplayParts(signature, allSignatures, 16 /* WriteArrowStyleSignature */); + addSignatureDisplayParts(signature, allSignatures, 262144 /* WriteArrowStyleSignature */); break; default: // Just signature @@ -88665,7 +90663,7 @@ var ts; displayParts.push(ts.spacePart()); displayParts.push(ts.operatorPart(58 /* EqualsToken */)); displayParts.push(ts.spacePart()); - ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 1024 /* InTypeAlias */)); + ts.addRange(displayParts, ts.typeToDisplayParts(typeChecker, typeChecker.getDeclaredTypeOfSymbol(symbol), enclosingDeclaration, 8388608 /* InTypeAlias */)); } if (symbolFlags & 384 /* Enum */) { prefixNextMeaning(); @@ -88714,7 +90712,7 @@ var ts; else if (declaration.kind !== 156 /* CallSignature */ && declaration.name) { addFullSymbolName(declaration.symbol); } - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, sourceFile, 32 /* WriteTypeArgumentsOfSignature */)); } else if (declaration.kind === 232 /* TypeAliasDeclaration */) { // Type alias type parameter @@ -88823,7 +90821,8 @@ var ts; // If the type is type parameter, format it specially if (type.symbol && type.symbol.flags & 262144 /* TypeParameter */) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplay(type, writer, enclosingDeclaration); + var param = typeChecker.typeParameterToDeclaration(type, enclosingDeclaration); + getPrinter().writeNode(4 /* Unspecified */, param, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -88878,6 +90877,12 @@ var ts; documentation = documentationFromAlias; } return { displayParts: displayParts, documentation: documentation, symbolKind: symbolKind, tags: tags }; + function getPrinter() { + if (!printer) { + printer = ts.createPrinter({ removeComments: true }); + } + return printer; + } function prefixNextMeaning() { if (displayParts.length) { displayParts.push(ts.lineBreakPart()); @@ -88899,7 +90904,7 @@ var ts; if (alias && symbolToDisplay === symbol) { symbolToDisplay = alias; } - var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */); + var fullSymbolDisplayParts = ts.symbolToDisplayParts(typeChecker, symbolToDisplay, enclosingDeclaration || sourceFile, /*meaning*/ undefined, 1 /* WriteTypeParametersOrArguments */ | 2 /* UseOnlyExternalAliasing */ | 4 /* AllowAnyNodeKind */); ts.addRange(displayParts, fullSymbolDisplayParts); } function addPrefixForAnyFunctionOrVar(symbol, symbolKind) { @@ -88929,7 +90934,7 @@ var ts; } } function addSignatureDisplayParts(signature, allSignatures, flags) { - ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 64 /* WriteTypeArgumentsOfSignature */)); + ts.addRange(displayParts, ts.signatureToDisplayParts(typeChecker, signature, enclosingDeclaration, flags | 32 /* WriteTypeArgumentsOfSignature */)); if (allSignatures.length > 1) { displayParts.push(ts.spacePart()); displayParts.push(ts.punctuationPart(19 /* OpenParenToken */)); @@ -88944,7 +90949,8 @@ var ts; } function writeTypeParametersOfSymbol(symbol, enclosingDeclaration) { var typeParameterParts = ts.mapToDisplayParts(function (writer) { - typeChecker.getSymbolDisplayBuilder().buildTypeParameterDisplayFromSymbol(symbol, writer, enclosingDeclaration); + var params = typeChecker.symbolToTypeParameterDeclarations(symbol, enclosingDeclaration); + getPrinter().writeList(26896 /* TypeParameters */, params, ts.getSourceFileOfNode(ts.getParseTreeNode(enclosingDeclaration)), writer); }); ts.addRange(displayParts, typeParameterParts); } @@ -90479,29 +92485,32 @@ var ts; return -1 /* Unknown */; } function computeIndentation(node, startLine, inheritedIndentation, parent, parentDynamicIndentation, effectiveParentStartLine) { - var indentation = inheritedIndentation; var delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; if (effectiveParentStartLine === startLine) { // if node is located on the same line with the parent // - inherit indentation from the parent // - push children if either parent of node itself has non-zero delta - indentation = startLine === lastIndentedLine - ? indentationOnLastIndentedLine - : parentDynamicIndentation.getIndentation(); - delta = Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta); + return { + indentation: startLine === lastIndentedLine ? indentationOnLastIndentedLine : parentDynamicIndentation.getIndentation(), + delta: Math.min(options.indentSize, parentDynamicIndentation.getDelta(node) + delta) + }; } - else if (indentation === -1 /* Unknown */) { - if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { - indentation = parentDynamicIndentation.getIndentation(); + else if (inheritedIndentation === -1 /* Unknown */) { + if (node.kind === 19 /* OpenParenToken */ && startLine === lastIndentedLine) { + // the is used for chaining methods formatting + // - we need to get the indentation on last line and the delta of parent + return { indentation: indentationOnLastIndentedLine, delta: parentDynamicIndentation.getDelta(node) }; + } + else if (formatting.SmartIndenter.childStartsOnTheSameLineWithElseInIfStatement(parent, node, startLine, sourceFile)) { + return { indentation: parentDynamicIndentation.getIndentation(), delta: delta }; } else { - indentation = parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node); + return { indentation: parentDynamicIndentation.getIndentation() + parentDynamicIndentation.getDelta(node), delta: delta }; } } - return { - indentation: indentation, - delta: delta - }; + else { + return { indentation: inheritedIndentation, delta: delta }; + } } function getFirstNonDecoratorTokenOfNode(node) { if (node.modifiers && node.modifiers.length) { @@ -90535,67 +92544,55 @@ var ts; case 18 /* CloseBraceToken */: case 22 /* CloseBracketToken */: case 20 /* CloseParenToken */: - return indentation + getEffectiveDelta(delta, container); + return indentation + getDelta(container); } return tokenIndentation !== -1 /* Unknown */ ? tokenIndentation : indentation; }, getIndentationForToken: function (line, kind, container) { - if (nodeStartLine !== line && node.decorators) { - if (kind === getFirstNonDecoratorTokenOfNode(node)) { - // if this token is the first token following the list of decorators, we do not need to indent - return indentation; - } - } - switch (kind) { - // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent - case 17 /* OpenBraceToken */: - case 18 /* CloseBraceToken */: - case 19 /* OpenParenToken */: - case 20 /* CloseParenToken */: - case 82 /* ElseKeyword */: - case 106 /* WhileKeyword */: - case 57 /* AtToken */: - return indentation; - case 41 /* SlashToken */: - case 29 /* GreaterThanToken */: { - if (container.kind === 252 /* JsxOpeningElement */ || - container.kind === 253 /* JsxClosingElement */ || - container.kind === 251 /* JsxSelfClosingElement */) { - return indentation; - } - break; - } - case 21 /* OpenBracketToken */: - case 22 /* CloseBracketToken */: { - if (container.kind !== 173 /* MappedType */) { - return indentation; - } - break; - } - } - // if token line equals to the line of containing node (this is a first token in the node) - use node indentation - return nodeStartLine !== line ? indentation + getEffectiveDelta(delta, container) : indentation; + return shouldAddDelta(line, kind, container) ? indentation + getDelta(container) : indentation; }, getIndentation: function () { return indentation; }, - getDelta: function (child) { return getEffectiveDelta(delta, child); }, + getDelta: getDelta, recomputeIndentation: function (lineAdded) { if (node.parent && formatting.SmartIndenter.shouldIndentChildNode(node.parent, node)) { - if (lineAdded) { - indentation += options.indentSize; - } - else { - indentation -= options.indentSize; - } - if (formatting.SmartIndenter.shouldIndentChildNode(node)) { - delta = options.indentSize; - } - else { - delta = 0; - } + indentation += lineAdded ? options.indentSize : -options.indentSize; + delta = formatting.SmartIndenter.shouldIndentChildNode(node) ? options.indentSize : 0; } } }; - function getEffectiveDelta(delta, child) { + function shouldAddDelta(line, kind, container) { + switch (kind) { + // open and close brace, 'else' and 'while' (in do statement) tokens has indentation of the parent + case 17 /* OpenBraceToken */: + case 18 /* CloseBraceToken */: + case 19 /* OpenParenToken */: + case 20 /* CloseParenToken */: + case 82 /* ElseKeyword */: + case 106 /* WhileKeyword */: + case 57 /* AtToken */: + return false; + case 41 /* SlashToken */: + case 29 /* GreaterThanToken */: + switch (container.kind) { + case 252 /* JsxOpeningElement */: + case 253 /* JsxClosingElement */: + case 251 /* JsxSelfClosingElement */: + return false; + } + break; + case 21 /* OpenBracketToken */: + case 22 /* CloseBracketToken */: + if (container.kind !== 173 /* MappedType */) { + return false; + } + break; + } + // if token line equals to the line of containing node (this is a first token in the node) - use node indentation + return nodeStartLine !== line + // if this token is the first token following the list of decorators, we do not need to indent + && !(node.decorators && kind === getFirstNonDecoratorTokenOfNode(node)); + } + function getDelta(child) { // Delta value should be zero when the node explicitly prevents indentation of the child node return formatting.SmartIndenter.nodeWillIndentChild(node, child, /*indentByDefault*/ true) ? delta : 0; } @@ -90618,7 +92615,7 @@ var ts; // context node is set to parent of the token after processing every token var childContextNode = contextNode; // if there are any tokens that logically belong to node and interleave child nodes - // such tokens will be consumed in processChildNode for for the child that follows them + // such tokens will be consumed in processChildNode for the child that follows them ts.forEachChild(node, function (child) { processChildNode(child, /*inheritedIndentation*/ -1 /* Unknown */, node, nodeDynamicIndentation, nodeStartLine, undecoratedNodeStartLine, /*isListItem*/ false); }, function (nodes) { @@ -90840,23 +92837,25 @@ var ts; var trimTrailingWhitespaces; var lineAction = 0 /* None */; if (rule) { - applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); - if (rule.action & (2 /* Space */ | 8 /* Delete */) && currentStartLine !== previousStartLine) { - lineAction = 2 /* LineRemoved */; - // Handle the case where the next line is moved to be the end of this line. - // In this case we don't indent the next line in the next pass. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); - } - } - else if (rule.action & 4 /* NewLine */ && currentStartLine === previousStartLine) { - lineAction = 1 /* LineAdded */; - // Handle the case where token2 is moved to the new line. - // In this case we indent token2 in the next pass but we set - // sameLineIndent flag to notify the indenter that the indentation is within the line. - if (currentParent.getStart(sourceFile) === currentItem.pos) { - dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); - } + lineAction = applyRuleEdits(rule, previousItem, previousStartLine, currentItem, currentStartLine); + switch (lineAction) { + case 2 /* LineRemoved */: + // Handle the case where the next line is moved to be the end of this line. + // In this case we don't indent the next line in the next pass. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ false); + } + break; + case 1 /* LineAdded */: + // Handle the case where token2 is moved to the new line. + // In this case we indent token2 in the next pass but we set + // sameLineIndent flag to notify the indenter that the indentation is within the line. + if (currentParent.getStart(sourceFile) === currentItem.pos) { + dynamicIndentation.recomputeIndentation(/*lineAddedByFormatting*/ true); + } + break; + default: + ts.Debug.assert(lineAction === 0 /* None */); } // We need to trim trailing whitespace between the tokens if they were on different lines, and no rule was applied to put them on the same line trimTrailingWhitespaces = !(rule.action & 8 /* Delete */) && rule.flags !== 1 /* CanDeleteNewLines */; @@ -91004,14 +93003,16 @@ var ts; } } function applyRuleEdits(rule, previousRange, previousStartLine, currentRange, currentStartLine) { + var onLaterLine = currentStartLine !== previousStartLine; switch (rule.action) { case 1 /* Ignore */: // no action required - return; + return 0 /* None */; case 8 /* Delete */: if (previousRange.end !== currentRange.pos) { // delete characters starting from t1.end up to t2.pos exclusive recordDelete(previousRange.end, currentRange.pos - previousRange.end); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } break; case 4 /* NewLine */: @@ -91019,25 +93020,27 @@ var ts; // if line1 and line2 are on subsequent lines then no edits are required - ok to exit // if line1 and line2 are separated with more than one newline - ok to exit since we cannot delete extra new lines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } // edit should not be applied if we have one line feed between elements var lineDelta = currentStartLine - previousStartLine; if (lineDelta !== 1) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, options.newLineCharacter); + return onLaterLine ? 0 /* None */ : 1 /* LineAdded */; } break; case 2 /* Space */: // exit early if we on different lines and rule cannot change number of newlines if (rule.flags !== 1 /* CanDeleteNewLines */ && previousStartLine !== currentStartLine) { - return; + return 0 /* None */; } var posDelta = currentRange.pos - previousRange.end; if (posDelta !== 1 || sourceFile.text.charCodeAt(previousRange.end) !== 32 /* space */) { recordReplace(previousRange.end, currentRange.pos - previousRange.end, " "); + return onLaterLine ? 2 /* LineRemoved */ : 0 /* None */; } - break; } + return 0 /* None */; } } var LineAction; @@ -91050,7 +93053,7 @@ var ts; * @param precedingToken pass `null` if preceding token was already computed and result was `undefined`. */ function getRangeOfEnclosingComment(sourceFile, position, onlyMultiLine, precedingToken, // tslint:disable-line:no-null-keyword - tokenAtPosition, predicate) { + tokenAtPosition, predicate) { if (tokenAtPosition === void 0) { tokenAtPosition = ts.getTokenAtPosition(sourceFile, position, /*includeJsDocComment*/ false); } var tokenStart = tokenAtPosition.getStart(sourceFile); if (tokenStart <= position && position < tokenAtPosition.getEnd()) { @@ -91149,12 +93152,12 @@ var ts; internedTabsIndentation = []; } if (internedTabsIndentation[tabs] === undefined) { - internedTabsIndentation[tabs] = tabString = repeat("\t", tabs); + internedTabsIndentation[tabs] = tabString = ts.repeatString("\t", tabs); } else { tabString = internedTabsIndentation[tabs]; } - return spaces ? tabString + repeat(" ", spaces) : tabString; + return spaces ? tabString + ts.repeatString(" ", spaces) : tabString; } else { var spacesString = void 0; @@ -91164,20 +93167,13 @@ var ts; internedSpacesIndentation = []; } if (internedSpacesIndentation[quotient] === undefined) { - spacesString = repeat(" ", options.indentSize * quotient); + spacesString = ts.repeatString(" ", options.indentSize * quotient); internedSpacesIndentation[quotient] = spacesString; } else { spacesString = internedSpacesIndentation[quotient]; } - return remainder ? spacesString + repeat(" ", remainder) : spacesString; - } - function repeat(value, count) { - var s = ""; - for (var i = 0; i < count; i++) { - s += value; - } - return s; + return remainder ? spacesString + ts.repeatString(" ", remainder) : spacesString; } } formatting.getIndentationString = getIndentationString; @@ -91842,7 +93838,7 @@ var ts; this.newLineCharacter = ts.getNewLineCharacter({ newLine: newLine }); } ChangeTracker.fromContext = function (context) { - return new ChangeTracker(context.newLineCharacter === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); + return new ChangeTracker(ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options) === "\n" ? 1 /* LineFeed */ : 0 /* CarriageReturnLineFeed */, context.formatContext); }; ChangeTracker.with = function (context, cb) { var tracker = ChangeTracker.fromContext(context); @@ -92397,6 +94393,38 @@ var ts; this.writer.write(s); this.setLastNonTriviaPosition(s, /*force*/ false); }; + Writer.prototype.writeKeyword = function (s) { + this.writer.writeKeyword(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeOperator = function (s) { + this.writer.writeOperator(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writePunctuation = function (s) { + this.writer.writePunctuation(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeParameter = function (s) { + this.writer.writeParameter(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeProperty = function (s) { + this.writer.writeProperty(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSpace = function (s) { + this.writer.writeSpace(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeStringLiteral = function (s) { + this.writer.writeStringLiteral(s); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; + Writer.prototype.writeSymbol = function (s, sym) { + this.writer.writeSymbol(s, sym); + this.setLastNonTriviaPosition(s, /*force*/ false); + }; Writer.prototype.writeTextOfNode = function (text, node) { this.writer.writeTextOfNode(text, node); }; @@ -92435,8 +94463,8 @@ var ts; Writer.prototype.isAtStartOfLine = function () { return this.writer.isAtStartOfLine(); }; - Writer.prototype.reset = function () { - this.writer.reset(); + Writer.prototype.clear = function () { + this.writer.clear(); this.lastNonTriviaPosition = 0; }; return Writer; @@ -92580,8 +94608,9 @@ var ts; // A map with the refactor code as key, the refactor itself as value // e.g. nonSuggestableRefactors[refactorCode] -> the refactor you want var refactors = ts.createMap(); - function registerRefactor(refactor) { - refactors.set(refactor.name, refactor); + /** @param name An unique code associated with each refactor. Does not have to be human-readable. */ + function registerRefactor(name, refactor) { + refactors.set(name, refactor); } refactor_1.registerRefactor = registerRefactor; function getApplicableRefactors(context) { @@ -93341,9 +95370,18 @@ var ts; } break; case 147 /* Parameter */: - var functionDeclaration = parent.parent; - if (functionDeclaration.parameters.length === 1) { - changes.deleteNode(sourceFile, parent); + var oldFunction = parent.parent; + if (ts.isArrowFunction(oldFunction) && oldFunction.parameters.length === 1) { + // Lambdas with exactly one parameter are special because, after removal, there + // must be an empty parameter list (i.e. `()`) and this won't necessarily be the + // case if the parameter is simply removed (e.g. in `x => 1`). + var newFunction = ts.updateArrowFunction(oldFunction, oldFunction.modifiers, oldFunction.typeParameters, + /*parameters*/ undefined, oldFunction.type, oldFunction.equalsGreaterThanToken, oldFunction.body); + // Drop leading and trailing trivia of the new function because we're only going + // to replace the span (vs the full span) of the old function - the old leading + // and trailing trivia will remain. + ts.suppressLeadingAndTrailingTrivia(newFunction); + changes.replaceRange(sourceFile, { pos: oldFunction.getStart(), end: oldFunction.end }, newFunction); } else { changes.deleteNodeInList(sourceFile, parent); @@ -93501,7 +95539,7 @@ var ts; return { span: ts.createTextSpanFromBounds(declaration.getStart(sourceFile), declaration.getEnd()), newText: newText }; } function typeString(type, checker) { - return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 8 /* NoTruncation */); + return checker.typeToString(type, /*enclosingDeclaration*/ undefined, 1 /* NoTruncation */); } function isTypeContainer(node) { // NOTE: Some locations are not handled yet: @@ -93733,7 +95771,6 @@ var ts; var symbolToken = ts.cast(ts.getTokenAtPosition(context.sourceFile, context.span.start, /*includeJsDocComment*/ false), ts.isIdentifier); return { host: context.host, - newLineCharacter: context.newLineCharacter, formatContext: context.formatContext, sourceFile: context.sourceFile, program: program, @@ -94001,7 +96038,7 @@ var ts; } function tryGetModuleNameFromTypeRoots(options, host, getCanonicalFileName, moduleFileName, addJsExtension) { var roots = ts.getEffectiveTypeRoots(options, host); - return roots && ts.firstDefined(roots, function (unNormalizedTypeRoot) { + return ts.firstDefined(roots, function (unNormalizedTypeRoot) { var typeRoot = ts.toPath(unNormalizedTypeRoot, /*basePath*/ undefined, getCanonicalFileName); if (ts.startsWith(moduleFileName, typeRoot)) { return removeExtensionAndIndexPostFix(moduleFileName.substring(typeRoot.length + 1), options, addJsExtension); @@ -94381,10 +96418,11 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, newLineCharacter = context.newLineCharacter, span = context.span; + var sourceFile = context.sourceFile, program = context.program, span = context.span; if (!ts.isInJavaScriptFile(sourceFile) || !ts.isCheckJsEnabledForFile(sourceFile, program.getCompilerOptions())) { return undefined; } + var newLineCharacter = ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options); return [{ description: ts.getLocaleSpecificMessage(ts.Diagnostics.Ignore_this_error_message), changes: [codefix.createFileTextChanges(sourceFile.fileName, [getIgnoreCommentLocationForLocation(sourceFile, span.start, newLineCharacter)])], @@ -94406,7 +96444,7 @@ var ts; fixIds: [fixId], getAllCodeActions: function (context) { return codefix.codeFixAllWithTextChanges(context, errorCodes, function (changes, err) { if (err.start !== undefined) { - changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, context.newLineCharacter)); + changes.push(getIgnoreCommentLocationForLocation(err.file, err.start, ts.getNewLineOrDefaultFromHost(context.host, context.formatContext.options))); } }); }, }); @@ -94501,8 +96539,8 @@ var ts; outputMethod(signature, modifiers, name, createStubbedMethodBody()); break; } - for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { - var signature = signatures_9[_i]; + for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) { + var signature = signatures_8[_i]; // Need to ensure nodes are fresh each time so they can have different positions. outputMethod(signature, getSynthesizedDeepClones(modifiers), ts.getSynthesizedDeepClone(name)); } @@ -94523,7 +96561,7 @@ var ts; } } function signatureToMethodDeclaration(checker, signature, enclosingDeclaration, modifiers, name, optional, body) { - var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, ts.NodeBuilderFlags.SuppressAnyReturnType); + var signatureDeclaration = checker.signatureToSignatureDeclaration(signature, 152 /* MethodDeclaration */, enclosingDeclaration, 256 /* SuppressAnyReturnType */); if (!signatureDeclaration) { return undefined; } @@ -94574,8 +96612,8 @@ var ts; var maxArgsSignature = signatures[0]; var minArgumentCount = signatures[0].minArgumentCount; var someSigHasRestParameter = false; - for (var _i = 0, signatures_10 = signatures; _i < signatures_10.length; _i++) { - var sig = signatures_10[_i]; + for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) { + var sig = signatures_9[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); if (sig.hasRestParameter) { someSigHasRestParameter = true; @@ -94822,7 +96860,7 @@ var ts; var typeIsAccessible = true; var writeText = function (text) { return str += text; }; return { - string: function () { return typeIsAccessible ? str : undefined; }, + getText: function () { return typeIsAccessible ? str : undefined; }, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, @@ -94831,6 +96869,15 @@ var ts; writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + write: writeText, + writeTextOfNode: writeText, + rawWrite: writeText, + writeLiteral: writeText, + getTextPos: function () { return 0; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return writeText(" "); }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -94847,8 +96894,8 @@ var ts; } function typeToString(type, enclosingDeclaration, checker) { var writer = getTypeAccessiblityWriter(checker); - checker.getSymbolDisplayBuilder().buildTypeDisplay(type, writer, enclosingDeclaration); - return writer.string(); + checker.writeType(type, enclosingDeclaration, /*flags*/ undefined, writer); + return writer.getText(); } var InferFromReference; (function (InferFromReference) { @@ -95307,14 +97354,10 @@ var ts; (function (refactor) { var annotateWithTypeFromJSDoc; (function (annotateWithTypeFromJSDoc) { + var refactorName = "Annotate with type from JSDoc"; var actionName = "annotate"; - var annotateTypeFromJSDoc = { - name: "Annotate with type from JSDoc", - description: ts.Diagnostics.Annotate_with_type_from_JSDoc.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(annotateTypeFromJSDoc); + var description = ts.Diagnostics.Annotate_with_type_from_JSDoc.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.isInJavaScriptFile(context.file)) { return undefined; @@ -95322,11 +97365,11 @@ var ts; var node = ts.getTokenAtPosition(context.file, context.startPosition, /*includeJsDocComment*/ false); if (hasUsableJSDoc(ts.findAncestor(node, isDeclarationWithType))) { return [{ - name: annotateTypeFromJSDoc.name, - description: annotateTypeFromJSDoc.description, + name: refactorName, + description: description, actions: [ { - description: annotateTypeFromJSDoc.description, + description: description, name: actionName } ] @@ -95536,15 +97579,11 @@ var ts; var refactor; (function (refactor) { var convertFunctionToES6Class; - (function (convertFunctionToES6Class_1) { + (function (convertFunctionToES6Class) { + var refactorName = "Convert to ES2015 class"; var actionName = "convert"; - var convertFunctionToES6Class = { - name: "Convert to ES2015 class", - description: ts.Diagnostics.Convert_function_to_an_ES2015_class.message, - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions - }; - refactor.registerRefactor(convertFunctionToES6Class); + var description = ts.Diagnostics.Convert_function_to_an_ES2015_class.message; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (!ts.isInJavaScriptFile(context.file)) { return undefined; @@ -95559,11 +97598,11 @@ var ts; if ((symbol.flags & 16 /* Function */) && symbol.members && (symbol.members.size > 0)) { return [ { - name: convertFunctionToES6Class.name, - description: convertFunctionToES6Class.description, + name: refactorName, + description: description, actions: [ { - description: convertFunctionToES6Class.description, + description: description, name: actionName } ] @@ -95779,13 +97818,8 @@ var ts; var refactor; (function (refactor) { var actionName = "Convert to ES6 module"; - var convertToEs6Module = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(convertToEs6Module); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_ES6_module); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition; if (!ts.isSourceFileJavaScript(file) || !file.commonJsModuleIndicator) { @@ -95794,11 +97828,11 @@ var ts; var node = ts.getTokenAtPosition(file, startPosition, /*includeJsDocComment*/ false); return !isAtTriggerLocation(file, node) ? undefined : [ { - name: convertToEs6Module.name, - description: convertToEs6Module.description, + name: actionName, + description: description, actions: [ { - description: convertToEs6Module.description, + description: description, name: actionName, }, ], @@ -96268,14 +98302,9 @@ var ts; var refactor; (function (refactor) { var extractSymbol; - (function (extractSymbol_1) { - var extractSymbol = { - name: "Extract Symbol", - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_symbol), - getAvailableActions: getAvailableActions, - getEditsForAction: getEditsForAction, - }; - refactor.registerRefactor(extractSymbol); + (function (extractSymbol) { + var refactorName = "Extract Symbol"; + refactor.registerRefactor(refactorName, { getAvailableActions: getAvailableActions, getEditsForAction: getEditsForAction }); /** * Compute the associated code actions * Exported for tests. @@ -96333,21 +98362,21 @@ var ts; var infos = []; if (functionActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_function), actions: functionActions }); } if (constantActions.length) { infos.push({ - name: extractSymbol.name, + name: refactorName, description: ts.getLocaleSpecificMessage(ts.Diagnostics.Extract_constant), actions: constantActions }); } return infos.length ? infos : undefined; } - extractSymbol_1.getAvailableActions = getAvailableActions; + extractSymbol.getAvailableActions = getAvailableActions; /* Exported for tests */ function getEditsForAction(context, actionName) { var rangeToExtract = getRangeToExtract(context.file, { start: context.startPosition, length: ts.getRefactorContextLength(context) }); @@ -96366,7 +98395,7 @@ var ts; } ts.Debug.fail("Unrecognized action name"); } - extractSymbol_1.getEditsForAction = getEditsForAction; + extractSymbol.getEditsForAction = getEditsForAction; // Move these into diagnostic messages if they become user-facing var Messages; (function (Messages) { @@ -96395,7 +98424,7 @@ var ts; Messages.cannotExtractToOtherFunctionLike = createMessage("Cannot extract method to a function-like scope that is not a function"); Messages.cannotExtractToJSClass = createMessage("Cannot extract constant to a class scope in JS"); Messages.cannotExtractToExpressionArrowFunction = createMessage("Cannot extract constant to an arrow function without a block"); - })(Messages = extractSymbol_1.Messages || (extractSymbol_1.Messages = {})); + })(Messages = extractSymbol.Messages || (extractSymbol.Messages = {})); var RangeFacts; (function (RangeFacts) { RangeFacts[RangeFacts["None"] = 0] = "None"; @@ -96682,7 +98711,7 @@ var ts; } } } - extractSymbol_1.getRangeToExtract = getRangeToExtract; + extractSymbol.getRangeToExtract = getRangeToExtract; function getStatementOrExpressionRange(node) { if (ts.isStatement(node)) { return [node]; @@ -96884,7 +98913,7 @@ var ts; var type = checker.getTypeOfSymbolAtLocation(usage.symbol, usage.node); // Widen the type so we don't emit nonsense annotations like "function fn(x: 3) {" type = checker.getBaseTypeOfLiteralType(type); - typeNode = checker.typeToTypeNode(type, scope, ts.NodeBuilderFlags.NoTruncation); + typeNode = checker.typeToTypeNode(type, scope, 1 /* NoTruncation */); } var paramDecl = ts.createParameter( /*decorators*/ undefined, @@ -96912,7 +98941,7 @@ var ts; // to avoid problems when there are literal types present if (ts.isExpression(node) && !isJS) { var contextualType = checker.getContextualType(node); - returnType = checker.typeToTypeNode(contextualType, scope, ts.NodeBuilderFlags.NoTruncation); + returnType = checker.typeToTypeNode(contextualType, scope, 1 /* NoTruncation */); } var _b = transformFunctionBody(node, exposedVariableDeclarations, writes, substitutions, !!(range.facts & RangeFacts.HasReturn)), body = _b.body, returnValueProperty = _b.returnValueProperty; ts.suppressLeadingAndTrailingTrivia(body); @@ -96980,7 +99009,7 @@ var ts; /*propertyName*/ undefined, /*name*/ ts.getSynthesizedDeepClone(variableDeclaration.name))); // Being returned through an object literal will have widened the type. - var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, ts.NodeBuilderFlags.NoTruncation); + var variableType = checker.typeToTypeNode(checker.getBaseTypeOfLiteralType(checker.getTypeAtLocation(variableDeclaration)), scope, 1 /* NoTruncation */); typeElements.push(ts.createPropertySignature( /*modifiers*/ undefined, /*name*/ variableDeclaration.symbol.name, @@ -97091,7 +99120,7 @@ var ts; var isJS = ts.isInJavaScriptFile(scope); var variableType = isJS || !checker.isContextSensitive(node) ? undefined - : checker.typeToTypeNode(checker.getContextualType(node), scope, ts.NodeBuilderFlags.NoTruncation); + : checker.typeToTypeNode(checker.getContextualType(node), scope, 1 /* NoTruncation */); var initializer = transformConstantInitializer(node, substitutions); ts.suppressLeadingAndTrailingTrivia(initializer); var changeTracker = ts.textChanges.ChangeTracker.fromContext(context); @@ -97817,15 +99846,11 @@ var ts; var refactor; (function (refactor) { var installTypesForPackage; - (function (installTypesForPackage_1) { + (function (installTypesForPackage) { + var refactorName = "Install missing types package"; var actionName = "install"; - var installTypesForPackage = { - name: "Install missing types package", - description: "Install missing types package", - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(installTypesForPackage); + var description = "Install missing types package"; + refactor.registerRefactor(refactorName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { if (ts.getStrictOptionValue(context.program.getCompilerOptions(), "noImplicitAny")) { // Then it will be available via `fixCannotFindModule`. @@ -97834,8 +99859,8 @@ var ts; var action = getAction(context); return action && [ { - name: installTypesForPackage.name, - description: installTypesForPackage.description, + name: refactorName, + description: description, actions: [ { description: action.description, @@ -97890,13 +99915,8 @@ var ts; var installTypesForPackage; (function (installTypesForPackage) { var actionName = "Convert to default import"; - var useDefaultImport = { - name: actionName, - description: ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import), - getEditsForAction: getEditsForAction, - getAvailableActions: getAvailableActions, - }; - refactor.registerRefactor(useDefaultImport); + var description = ts.getLocaleSpecificMessage(ts.Diagnostics.Convert_to_default_import); + refactor.registerRefactor(actionName, { getEditsForAction: getEditsForAction, getAvailableActions: getAvailableActions }); function getAvailableActions(context) { var file = context.file, startPosition = context.startPosition, program = context.program; if (!program.getCompilerOptions().allowSyntheticDefaultImports) { @@ -97913,11 +99933,11 @@ var ts; } return [ { - name: useDefaultImport.name, - description: useDefaultImport.description, + name: actionName, + description: description, actions: [ { - description: useDefaultImport.description, + description: description, name: actionName, }, ], @@ -98528,9 +100548,9 @@ var ts; function getDeclarationName(declaration) { var name = ts.getNameOfDeclaration(declaration); if (name) { - var result_7 = ts.getTextOfIdentifierOrLiteral(name); - if (result_7 !== undefined) { - return result_7; + var result_6 = ts.getTextOfIdentifierOrLiteral(name); + if (result_6 !== undefined) { + return result_6; } if (name.kind === 145 /* ComputedPropertyName */) { var expr = name.expression; @@ -98815,8 +100835,7 @@ var ts; sourceFile.scriptSnapshot = scriptSnapshot; } function createLanguageServiceSourceFile(fileName, scriptSnapshot, scriptTarget, version, setNodeParents, scriptKind) { - var text = scriptSnapshot.getText(0, scriptSnapshot.getLength()); - var sourceFile = ts.createSourceFile(fileName, text, scriptTarget, setNodeParents, scriptKind); + var sourceFile = ts.createSourceFile(fileName, ts.getSnapshotText(scriptSnapshot), scriptTarget, setNodeParents, scriptKind); setSourceFileFields(sourceFile, scriptSnapshot, version); return sourceFile; } @@ -98980,7 +100999,7 @@ var ts; getCancellationToken: function () { return cancellationToken; }, getCanonicalFileName: getCanonicalFileName, useCaseSensitiveFileNames: function () { return useCaseSensitivefileNames; }, - getNewLine: function () { return ts.getNewLineCharacter(newSettings, { newLine: ts.getNewLineOrDefaultFromHost(host) }); }, + getNewLine: function () { return ts.getNewLineCharacter(newSettings, function () { return ts.getNewLineOrDefaultFromHost(host); }); }, getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); }, writeFile: ts.noop, getCurrentDirectory: function () { return currentDirectory; }, @@ -98990,7 +101009,7 @@ var ts; var path = ts.toPath(fileName, currentDirectory, getCanonicalFileName); var entry = hostCache.getEntryByPath(path); if (entry) { - return ts.isString(entry) ? undefined : entry.scriptSnapshot.getText(0, entry.scriptSnapshot.getLength()); + return ts.isString(entry) ? undefined : ts.getSnapshotText(entry.scriptSnapshot); } return host.readFile && host.readFile(fileName); }, @@ -99227,10 +101246,10 @@ var ts; function getOccurrencesAtPosition(fileName, position) { var results = getOccurrencesAtPositionCore(fileName, position); if (results) { - var sourceFile_1 = getCanonicalFileName(ts.normalizeSlashes(fileName)); + var sourceFile_2 = getCanonicalFileName(ts.normalizeSlashes(fileName)); // Get occurrences only supports reporting occurrences for the file queried. So // filter down to that list. - results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_1; }); + results = ts.filter(results, function (r) { return getCanonicalFileName(ts.normalizeSlashes(r.fileName)) === sourceFile_2; }); } return results; } @@ -99492,20 +101511,18 @@ var ts; synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var span = ts.createTextSpanFromBounds(start, end); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); return ts.flatMap(ts.deduplicate(errorCodes, ts.equateValues, ts.compareValues), function (errorCode) { cancellationToken.throwIfCancellationRequested(); - return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getFixes({ errorCode: errorCode, sourceFile: sourceFile, span: span, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); }); } function getCombinedCodeFix(scope, fixId, formatOptions) { synchronizeHostData(); ts.Debug.assert(scope.type === "file"); var sourceFile = getValidSourceFile(scope.fileName); - var newLineCharacter = ts.getNewLineOrDefaultFromHost(host); var formatContext = ts.formatting.getFormatContext(formatOptions); - return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, newLineCharacter: newLineCharacter, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); + return ts.codefix.getAllFixes({ fixId: fixId, sourceFile: sourceFile, program: program, host: host, cancellationToken: cancellationToken, formatContext: formatContext }); } function applyCodeActionCommand(fileName, actionOrUndefined) { var action = typeof fileName === "string" ? actionOrUndefined : fileName; @@ -99693,7 +101710,6 @@ var ts; startPosition: startPosition, endPosition: endPosition, program: getProgram(), - newLineCharacter: formatOptions ? formatOptions.newLineCharacter : host.getNewLine(), host: host, formatContext: ts.formatting.getFormatContext(formatOptions), cancellationToken: cancellationToken, @@ -99829,20 +101845,20 @@ var ts; function getPropertySymbolsFromType(type, propName) { var name = ts.unescapeLeadingUnderscores(ts.getTextOfPropertyName(propName)); if (name && type) { - var result_8 = []; + 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_8.push(symbol); + result_7.push(symbol); } }); - return result_8; + return result_7; } if (symbol) { - result_8.push(symbol); - return result_8; + result_7.push(symbol); + return result_7; } } return undefined; @@ -101121,7 +103137,7 @@ var ts; var _this = this; return this.forwardJSONCall("getPreProcessedFileInfo('" + fileName + "')", function () { // for now treat files as JavaScript - var result = ts.preProcessFile(sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()), /* readImportFiles */ true, /* detectJavaScriptImports */ true); + var result = ts.preProcessFile(ts.getSnapshotText(sourceTextSnapshot), /* readImportFiles */ true, /* detectJavaScriptImports */ true); return { referencedFiles: _this.convertFileReferences(result.referencedFiles), importedFiles: _this.convertFileReferences(result.importedFiles), @@ -101156,8 +103172,7 @@ var ts; CoreServicesShimObject.prototype.getTSConfigFileInfo = function (fileName, sourceTextSnapshot) { var _this = this; return this.forwardJSONCall("getTSConfigFileInfo('" + fileName + "')", function () { - var text = sourceTextSnapshot.getText(0, sourceTextSnapshot.getLength()); - var result = ts.parseJsonText(fileName, text); + var result = ts.parseJsonText(fileName, ts.getSnapshotText(sourceTextSnapshot)); var normalizedFileName = ts.normalizeSlashes(fileName); var configFile = ts.parseJsonSourceFileConfigFileContent(result, _this.host, ts.getDirectoryPath(normalizedFileName), /*existingOptions*/ {}, normalizedFileName); return { diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 6196e0ef01f..24454f0f7be 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -46,24 +46,6 @@ var ts; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); - var NodeBuilderFlags; - (function (NodeBuilderFlags) { - NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None"; - NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation"; - NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature"; - NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType"; - NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType"; - NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName"; - NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 1024] = "AllowThisInObjectLiteral"; - NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 2048] = "AllowQualifedNameInPlaceOfIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 8192] = "AllowAnonymousIdentifier"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 16384] = "AllowEmptyUnionOrIntersection"; - NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 32768] = "AllowEmptyTuple"; - NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 60416] = "IgnoreErrors"; - NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 1048576] = "InObjectTypeLiteral"; - NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias"; - })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {})); var TypeReferenceSerializationKind; (function (TypeReferenceSerializationKind) { TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown"; @@ -160,7 +142,7 @@ var ts; var ts; (function (ts) { ts.versionMajorMinor = "2.7"; - ts.version = ts.versionMajorMinor + ".0"; + ts.version = ts.versionMajorMinor + ".1"; })(ts || (ts = {})); (function (ts) { function isExternalModuleNameRelative(moduleName) { @@ -169,6 +151,7 @@ var ts; ts.isExternalModuleNameRelative = isExternalModuleNameRelative; })(ts || (ts = {})); (function (ts) { + ts.emptyArray = []; function createDictionaryObject() { var map = Object.create(null); map.__ = undefined; @@ -294,6 +277,9 @@ var ts; } ts.forEach = forEach; function firstDefined(array, callback) { + if (array === undefined) { + return undefined; + } for (var i = 0; i < array.length; i++) { var result = callback(array[i], i); if (result !== undefined) { @@ -1304,6 +1290,8 @@ var ts; ts.returnTrue = returnTrue; function identity(x) { return x; } ts.identity = identity; + function toLowerCase(x) { return x.toLowerCase(); } + ts.toLowerCase = toLowerCase; function notImplemented() { throw new Error("Not implemented"); } @@ -1631,7 +1619,7 @@ var ts; return p2 + 1; } if (path.charCodeAt(1) === 58) { - if (path.charCodeAt(2) === 47) + if (path.charCodeAt(2) === 47 || path.charCodeAt(2) === 92) return 3; } if (path.lastIndexOf("file:///", 0) === 0) { @@ -2287,10 +2275,10 @@ var ts; } function Signature() { } function Node(kind, pos, end) { - this.id = 0; - this.kind = kind; this.pos = pos; this.end = end; + this.kind = kind; + this.id = 0; this.flags = 0; this.modifierFlagsCache = 0; this.transformFlags = 0; @@ -2417,9 +2405,7 @@ var ts; } } function createGetCanonicalFileName(useCaseSensitiveFileNames) { - return useCaseSensitiveFileNames - ? (function (fileName) { return fileName; }) - : (function (fileName) { return fileName.toLowerCase(); }); + return useCaseSensitiveFileNames ? identity : toLowerCase; } ts.createGetCanonicalFileName = createGetCanonicalFileName; function matchPatternOrExact(patternStrings, candidate) { @@ -2516,170 +2502,16 @@ var ts; return function (arg) { return f(arg) && g(arg); }; } ts.and = and; + function or(f, g) { + return function (arg) { return f(arg) || g(arg); }; + } + ts.or = or; function assertTypeIsNever(_) { } ts.assertTypeIsNever = assertTypeIsNever; - function createCachedDirectoryStructureHost(host) { - var cachedReadDirectoryResult = createMap(); - var getCurrentDirectory = memoize(function () { return host.getCurrentDirectory(); }); - var getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); - return { - useCaseSensitiveFileNames: host.useCaseSensitiveFileNames, - newLine: host.newLine, - readFile: function (path, encoding) { return host.readFile(path, encoding); }, - write: function (s) { return host.write(s); }, - writeFile: writeFile, - fileExists: fileExists, - directoryExists: directoryExists, - createDirectory: createDirectory, - getCurrentDirectory: getCurrentDirectory, - getDirectories: getDirectories, - readDirectory: readDirectory, - addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory, - addOrDeleteFile: addOrDeleteFile, - clearCache: clearCache, - exit: function (code) { return host.exit(code); } - }; - function toPath(fileName) { - return ts.toPath(fileName, getCurrentDirectory(), getCanonicalFileName); - } - function getCachedFileSystemEntries(rootDirPath) { - return cachedReadDirectoryResult.get(rootDirPath); - } - function getCachedFileSystemEntriesForBaseDir(path) { - return getCachedFileSystemEntries(getDirectoryPath(path)); - } - function getBaseNameOfFileName(fileName) { - return getBaseFileName(normalizePath(fileName)); - } - function createCachedFileSystemEntries(rootDir, rootDirPath) { - var resultFromHost = { - files: map(host.readDirectory(rootDir, undefined, undefined, ["*.*"]), getBaseNameOfFileName) || [], - directories: host.getDirectories(rootDir) || [] - }; - cachedReadDirectoryResult.set(rootDirPath, resultFromHost); - return resultFromHost; - } - function tryReadDirectory(rootDir, rootDirPath) { - var cachedResult = getCachedFileSystemEntries(rootDirPath); - if (cachedResult) { - return cachedResult; - } - try { - return createCachedFileSystemEntries(rootDir, rootDirPath); - } - catch (_e) { - Debug.assert(!cachedReadDirectoryResult.has(rootDirPath)); - return undefined; - } - } - function fileNameEqual(name1, name2) { - return getCanonicalFileName(name1) === getCanonicalFileName(name2); - } - function hasEntry(entries, name) { - return some(entries, function (file) { return fileNameEqual(file, name); }); - } - function updateFileSystemEntry(entries, baseName, isValid) { - if (hasEntry(entries, baseName)) { - if (!isValid) { - return filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); }); - } - } - else if (isValid) { - return entries.push(baseName); - } - } - function writeFile(fileName, data, writeByteOrderMark) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - if (result) { - updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), true); - } - return host.writeFile(fileName, data, writeByteOrderMark); - } - function fileExists(fileName) { - var path = toPath(fileName); - var result = getCachedFileSystemEntriesForBaseDir(path); - return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) || - host.fileExists(fileName); - } - function directoryExists(dirPath) { - var path = toPath(dirPath); - return cachedReadDirectoryResult.has(path) || host.directoryExists(dirPath); - } - function createDirectory(dirPath) { - var path = toPath(dirPath); - var result = getCachedFileSystemEntriesForBaseDir(path); - var baseFileName = getBaseNameOfFileName(dirPath); - if (result) { - updateFileSystemEntry(result.directories, baseFileName, true); - } - host.createDirectory(dirPath); - } - function getDirectories(rootDir) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return result.directories.slice(); - } - return host.getDirectories(rootDir); - } - function readDirectory(rootDir, extensions, excludes, includes, depth) { - var rootDirPath = toPath(rootDir); - var result = tryReadDirectory(rootDir, rootDirPath); - if (result) { - return matchFiles(rootDir, extensions, excludes, includes, host.useCaseSensitiveFileNames, getCurrentDirectory(), depth, getFileSystemEntries); - } - return host.readDirectory(rootDir, extensions, excludes, includes, depth); - function getFileSystemEntries(dir) { - var path = toPath(dir); - if (path === rootDirPath) { - return result; - } - return getCachedFileSystemEntries(path) || createCachedFileSystemEntries(dir, path); - } - } - function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) { - var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath); - if (existingResult) { - clearCache(); - } - else { - var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath); - if (parentResult) { - var baseName = getBaseNameOfFileName(fileOrDirectory); - if (parentResult) { - var fsQueryResult = { - fileExists: host.fileExists(fileOrDirectoryPath), - directoryExists: host.directoryExists(fileOrDirectoryPath) - }; - if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) { - clearCache(); - } - else { - updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists); - } - return fsQueryResult; - } - } - } - } - function addOrDeleteFile(fileName, filePath, eventKind) { - if (eventKind === ts.FileWatcherEventKind.Changed) { - return; - } - var parentResult = getCachedFileSystemEntriesForBaseDir(filePath); - if (parentResult) { - updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created); - } - } - function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) { - updateFileSystemEntry(parentResult.files, baseName, fileExists); - } - function clearCache() { - cachedReadDirectoryResult.clear(); - } - } - ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost; + ts.emptyFileSystemEntries = { + files: ts.emptyArray, + directories: ts.emptyArray + }; function singleElementArray(t) { return t === undefined ? undefined : [t]; } @@ -2920,7 +2752,7 @@ var ts; return { files: files, directories: directories }; } catch (e) { - return { files: [], directories: [] }; + return ts.emptyFileSystemEntries; } } function readDirectory(path, extensions, excludes, includes, depth) { @@ -3029,7 +2861,12 @@ var ts; process.exit(exitCode); }, realpath: function (path) { - return _fs.realpathSync(path); + try { + return _fs.realpathSync(path); + } + catch (_a) { + return path; + } }, debugMode: ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }), tryEnableSourceMapsForHost: function () { @@ -3614,6 +3451,7 @@ var ts; The_containing_function_or_module_body_is_too_large_for_control_flow_analysis: diag(2563, ts.DiagnosticCategory.Error, "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563", "The containing function or module body is too large for control flow analysis."), Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor: diag(2564, ts.DiagnosticCategory.Error, "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564", "Property '{0}' has no initializer and is not definitely assigned in the constructor."), Property_0_is_used_before_being_assigned: diag(2565, ts.DiagnosticCategory.Error, "Property_0_is_used_before_being_assigned_2565", "Property '{0}' is used before being assigned."), + A_rest_element_cannot_have_a_property_name: diag(2566, ts.DiagnosticCategory.Error, "A_rest_element_cannot_have_a_property_name_2566", "A rest element cannot have a property name."), JSX_element_attributes_type_0_may_not_be_a_union_type: diag(2600, ts.DiagnosticCategory.Error, "JSX_element_attributes_type_0_may_not_be_a_union_type_2600", "JSX element attributes type '{0}' may not be a union type."), The_return_type_of_a_JSX_element_constructor_must_return_an_object_type: diag(2601, ts.DiagnosticCategory.Error, "The_return_type_of_a_JSX_element_constructor_must_return_an_object_type_2601", "The return type of a JSX element constructor must return an object type."), JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist: diag(2602, ts.DiagnosticCategory.Error, "JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist_2602", "JSX element implicitly has type 'any' because the global type 'JSX.Element' does not exist."), @@ -3873,7 +3711,7 @@ var ts; Report_errors_for_fallthrough_cases_in_switch_statement: diag(6076, ts.DiagnosticCategory.Message, "Report_errors_for_fallthrough_cases_in_switch_statement_6076", "Report errors for fallthrough cases in switch statement."), Do_not_report_errors_on_unreachable_code: diag(6077, ts.DiagnosticCategory.Message, "Do_not_report_errors_on_unreachable_code_6077", "Do not report errors on unreachable code."), Disallow_inconsistently_cased_references_to_the_same_file: diag(6078, ts.DiagnosticCategory.Message, "Disallow_inconsistently_cased_references_to_the_same_file_6078", "Disallow inconsistently-cased references to the same file."), - Specify_library_files_to_be_included_in_the_compilation_Colon: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_Colon_6079", "Specify library files to be included in the compilation: "), + Specify_library_files_to_be_included_in_the_compilation: diag(6079, ts.DiagnosticCategory.Message, "Specify_library_files_to_be_included_in_the_compilation_6079", "Specify library files to be included in the compilation."), Specify_JSX_code_generation_Colon_preserve_react_native_or_react: diag(6080, ts.DiagnosticCategory.Message, "Specify_JSX_code_generation_Colon_preserve_react_native_or_react_6080", "Specify JSX code generation: 'preserve', 'react-native', or 'react'."), File_0_has_an_unsupported_extension_so_skipping_it: diag(6081, ts.DiagnosticCategory.Message, "File_0_has_an_unsupported_extension_so_skipping_it_6081", "File '{0}' has an unsupported extension, so skipping it."), Only_amd_and_system_modules_are_supported_alongside_0: diag(6082, ts.DiagnosticCategory.Error, "Only_amd_and_system_modules_are_supported_alongside_0_6082", "Only 'amd' and 'system' modules are supported alongside --{0}."), @@ -3982,6 +3820,7 @@ var ts; Enable_strict_checking_of_property_initialization_in_classes: diag(6187, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_property_initialization_in_classes_6187", "Enable strict checking of property initialization in classes."), Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."), Multiple_consecutive_numeric_separators_are_not_permitted: diag(6189, ts.DiagnosticCategory.Error, "Multiple_consecutive_numeric_separators_are_not_permitted_6189", "Multiple consecutive numeric separators are not permitted."), + Found_package_json_at_0_Package_ID_is_1: diag(6190, ts.DiagnosticCategory.Message, "Found_package_json_at_0_Package_ID_is_1_6190", "Found 'package.json' at '{0}'. Package ID is '{1}'."), 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."), @@ -4091,7 +3930,6 @@ var ts; Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"), Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"), Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"), - Extract_symbol: diag(95003, ts.DiagnosticCategory.Message, "Extract_symbol_95003", "Extract symbol"), Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"), Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"), Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"), @@ -4110,7 +3948,6 @@ var ts; })(ts || (ts = {})); var ts; (function (ts) { - ts.emptyArray = []; ts.resolvingEmptyArray = []; ts.emptyMap = ts.createMap(); ts.emptyUnderscoreEscapedMap = ts.emptyMap; @@ -4133,15 +3970,24 @@ var ts; var str = ""; var writeText = function (text) { return str += text; }; return { - string: function () { return str; }, + getText: function () { return str; }, + write: writeText, + rawWrite: writeText, + writeTextOfNode: writeText, writeKeyword: writeText, writeOperator: writeText, writePunctuation: writeText, writeSpace: writeText, writeStringLiteral: writeText, + writeLiteral: writeText, writeParameter: writeText, writeProperty: writeText, writeSymbol: writeText, + getTextPos: function () { return str.length; }, + getLine: function () { return 0; }, + getColumn: function () { return 0; }, + getIndent: function () { return 0; }, + isAtStartOfLine: function () { return false; }, writeLine: function () { return str += " "; }, increaseIndent: ts.noop, decreaseIndent: ts.noop, @@ -4153,10 +3999,10 @@ var ts; }; } function usingSingleLineStringWriter(action) { - var oldString = stringWriter.string(); + var oldString = stringWriter.getText(); try { action(stringWriter); - return stringWriter.string(); + return stringWriter.getText(); } finally { stringWriter.clear(); @@ -4197,6 +4043,12 @@ var ts; function packageIdIsEqual(a, b) { return a === b || a && b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version; } + function packageIdToString(_a) { + var name = _a.name, subModuleName = _a.subModuleName, version = _a.version; + var fullName = subModuleName ? name + "/" + subModuleName : name; + return fullName + "@" + version; + } + ts.packageIdToString = packageIdToString; function typeDirectiveIsEqualTo(oldResolution, newResolution) { return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary; } @@ -5441,41 +5293,30 @@ var ts; node.parameters[0].name.escapedText === "new"; } ts.isJSDocConstructSignature = isJSDocConstructSignature; - function getAllJSDocs(node) { - if (ts.isJSDocTypedefTag(node)) { - return [node.parent]; - } - return getJSDocCommentsAndTags(node); - } - ts.getAllJSDocs = getAllJSDocs; function getSourceOfAssignment(node) { return ts.isExpressionStatement(node) && node.expression && ts.isBinaryExpression(node.expression) && node.expression.operatorToken.kind === 58 && node.expression.right; } - ts.getSourceOfAssignment = getSourceOfAssignment; function getSingleInitializerOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0].initializer === child) && node.declarationList.declarations[0].initializer; } - ts.getSingleInitializerOfVariableStatement = getSingleInitializerOfVariableStatement; function getSingleVariableOfVariableStatement(node, child) { return ts.isVariableStatement(node) && node.declarationList.declarations.length > 0 && (!child || node.declarationList.declarations[0] === child) && node.declarationList.declarations[0]; } - ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement; function getNestedModuleDeclaration(node) { return node.kind === 234 && node.body && node.body.kind === 234 && node.body; } - ts.getNestedModuleDeclaration = getNestedModuleDeclaration; function getJSDocCommentsAndTags(node) { var result; getJSDocCommentsAndTagsWorker(node); @@ -5598,6 +5439,29 @@ var ts; return getAssignmentTargetKind(node) !== 0; } ts.isAssignmentTarget = isAssignmentTarget; + function isNodeWithPossibleHoistedDeclaration(node) { + switch (node.kind) { + case 208: + case 209: + case 221: + case 212: + case 222: + case 236: + case 261: + case 262: + case 223: + case 215: + case 216: + case 217: + case 213: + case 214: + case 225: + case 264: + return true; + } + return false; + } + ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration; function walkUp(node, kind) { while (node && node.kind === kind) { node = node.parent; @@ -6325,7 +6189,19 @@ var ts; getColumn: function () { return lineStart ? indent * getIndentSize() + 1 : output.length - linePos + 1; }, getText: function () { return output; }, isAtStartOfLine: function () { return lineStart; }, - reset: reset + clear: reset, + reportInaccessibleThisError: ts.noop, + reportPrivateInBaseOfClassExpression: ts.noop, + reportInaccessibleUniqueSymbolError: ts.noop, + trackSymbol: ts.noop, + writeKeyword: write, + writeOperator: write, + writeParameter: write, + writeProperty: write, + writePunctuation: write, + writeSpace: write, + writeStringLiteral: write, + writeSymbol: write }; } ts.createTextWriter = createTextWriter; @@ -6875,14 +6751,14 @@ var ts; ts.convertToBase64 = convertToBase64; var carriageReturnLineFeed = "\r\n"; var lineFeed = "\n"; - function getNewLineCharacter(options, system) { + function getNewLineCharacter(options, getNewLine) { switch (options.newLine) { case 0: return carriageReturnLineFeed; case 1: return lineFeed; } - return system ? system.newLine : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; + return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed; } ts.getNewLineCharacter = getNewLineCharacter; function formatEnum(value, enumObject, isFlags) { @@ -7855,7 +7731,7 @@ var ts; } ts.isDeleteExpression = isDeleteExpression; function isTypeOfExpression(node) { - return node.kind === 192; + return node.kind === 190; } ts.isTypeOfExpression = isTypeOfExpression; function isVoidExpression(node) { @@ -8299,7 +8175,7 @@ var ts; } ts.isStringTextContainingNode = isStringTextContainingNode; function isGeneratedIdentifier(node) { - return ts.isIdentifier(node) && node.autoGenerateKind > 0; + return ts.isIdentifier(node) && (node.autoGenerateFlags & 7) > 0; } ts.isGeneratedIdentifier = isGeneratedIdentifier; function isModifierKind(token) { @@ -10710,8 +10586,8 @@ var ts; case 177: return visitNodes(cbNode, cbNodes, node.decorators) || visitNodes(cbNode, cbNodes, node.modifiers) || - visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.dotDotDotToken) || + visitNode(cbNode, node.propertyName) || visitNode(cbNode, node.name) || visitNode(cbNode, node.initializer); case 161: @@ -15074,7 +14950,6 @@ var ts; return result; } scanner.scanRange(start + 3, length - 5, function () { - var advanceToken = true; var state = 1; var margin = undefined; var indent = start - Math.max(content.lastIndexOf("\n", start), 0) + 4; @@ -15101,7 +14976,6 @@ var ts; removeTrailingNewlines(comments); parseTag(indent); state = 0; - advanceToken = false; margin = undefined; indent++; } @@ -15146,13 +15020,7 @@ var ts; pushComment(scanner.getTokenText()); break; } - if (advanceToken) { - t = nextJSDocToken(); - } - else { - advanceToken = true; - t = currentToken; - } + t = nextJSDocToken(); } removeLeadingNewlines(comments); removeTrailingNewlines(comments); @@ -15236,7 +15104,8 @@ var ts; if (!tag) { return; } - addTag(tag, parseTagComments(indent + tag.end - tag.pos)); + tag.comment = parseTagComments(indent + tag.end - tag.pos); + addTag(tag); } function parseTagComments(indent) { var comments = []; @@ -15260,6 +15129,7 @@ var ts; indent = 0; break; case 57: + scanner.setTextPos(scanner.getTextPos() - 1); case 1: break loop; case 5: @@ -15289,7 +15159,7 @@ var ts; } removeLeadingNewlines(comments); removeTrailingNewlines(comments); - return comments; + return comments.length === 0 ? undefined : comments.join(""); } function parseUnknownTag(atToken, tagName) { var result = createNode(281, atToken.pos); @@ -15297,8 +15167,7 @@ var ts; result.tagName = tagName; return finishNode(result); } - function addTag(tag, comments) { - tag.comment = comments.join(""); + function addTag(tag) { if (!tags) { tags = [tag]; tagsPos = tag.pos; @@ -15556,33 +15425,43 @@ var ts; if (!tagName) { return false; } + var t; switch (tagName.escapedText) { case "type": return target === 0 && parseTypeTag(atToken, tagName); case "prop": case "property": - return target === 0 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 0; + break; case "arg": case "argument": case "param": - return target === 1 && parseParameterOrPropertyTag(atToken, tagName, target); + t = 1; + break; + default: + return false; } - return false; + if (target !== t) { + return false; + } + var tag = parseParameterOrPropertyTag(atToken, tagName, target); + tag.comment = parseTagComments(tag.end - tag.pos); + return tag; } function parseTemplateTag(atToken, tagName) { - if (ts.forEach(tags, function (t) { return t.kind === 287; })) { + if (ts.some(tags, ts.isJSDocTemplateTag)) { parseErrorAtPosition(tagName.pos, scanner.getTokenPos() - tagName.pos, ts.Diagnostics._0_tag_already_specified, tagName.escapedText); } var typeParameters = []; var typeParametersPos = getNodePos(); while (true) { - var name = parseJSDocIdentifierName(); + var typeParameter = createNode(146); + var name = parseJSDocIdentifierNameWithOptionalBraces(); skipWhitespace(); if (!name) { parseErrorAtPosition(scanner.getStartPos(), 0, ts.Diagnostics.Identifier_expected); return undefined; } - var typeParameter = createNode(146, name.pos); typeParameter.name = name; finishNode(typeParameter); typeParameters.push(typeParameter); @@ -15601,6 +15480,14 @@ var ts; finishNode(result); return result; } + function parseJSDocIdentifierNameWithOptionalBraces() { + var parsedBrace = parseOptional(17); + var res = parseJSDocIdentifierName(); + if (parsedBrace) { + parseExpected(18); + } + return res; + } function nextJSDocToken() { return currentToken = scanner.scanJSDocToken(); } @@ -16069,7 +15956,7 @@ var ts; }, showInSimplifiedHelpView: true, category: ts.Diagnostics.Basic_Options, - description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation_Colon + description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation }, { name: "allowJs", @@ -18461,7 +18348,9 @@ var ts; } var resolvedFromFile = loadModuleFromFile(extensions, candidate, failedLookupLocations, onlyRecordFailures, state); if (resolvedFromFile) { - return noPackageId(resolvedFromFile); + var nm = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile.path) : undefined; + var packageId = nm && getPackageJsonInfo(nm.packageDirectory, nm.subModuleName, failedLookupLocations, false, state).packageId; + return withPackageId(packageId, resolvedFromFile); } } if (!onlyRecordFailures) { @@ -18475,6 +18364,30 @@ var ts; } return loadNodeModuleFromDirectory(extensions, candidate, failedLookupLocations, onlyRecordFailures, state, considerPackageJson); } + var nodeModulesPathPart = "/node_modules/"; + function parseNodeModuleFromPath(path) { + path = ts.normalizePath(path); + var idx = path.lastIndexOf(nodeModulesPathPart); + if (idx === -1) { + return undefined; + } + var indexAfterNodeModules = idx + nodeModulesPathPart.length; + var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules); + if (path.charCodeAt(indexAfterNodeModules) === 64) { + indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName); + } + var packageDirectory = path.slice(0, indexAfterPackageName); + var subModuleName = removeExtensionAndIndex(path.slice(indexAfterPackageName + 1)); + return { packageDirectory: packageDirectory, subModuleName: subModuleName }; + } + function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) { + var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1); + return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex; + } + function removeExtensionAndIndex(path) { + var noExtension = ts.removeFileExtension(path); + return noExtension === "index" ? "" : ts.removeSuffix(noExtension, "/index"); + } function directoryProbablyExists(directoryName, host) { return !host.directoryExists || host.directoryExists(directoryName); } @@ -18553,13 +18466,18 @@ var ts; var directoryExists = !onlyRecordFailures && directoryProbablyExists(nodeModuleDirectory, host); var packageJsonPath = pathToPackageJson(nodeModuleDirectory); if (directoryExists && host.fileExists(packageJsonPath)) { - if (traceEnabled) { - trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); - } var packageJsonContent = readJson(packageJsonPath, host); var packageId = typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string" ? { name: packageJsonContent.name, subModuleName: subModuleName, version: packageJsonContent.version } : undefined; + if (traceEnabled) { + if (packageId) { + trace(host, ts.Diagnostics.Found_package_json_at_0_Package_ID_is_1, packageJsonPath, ts.packageIdToString(packageId)); + } + else { + trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath); + } + } return { found: true, packageJsonContent: packageJsonContent, packageId: packageId }; } else { @@ -18702,13 +18620,17 @@ var ts; function getPackageNameFromAtTypesDirectory(mangledName) { var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/"); if (withoutAtTypePrefix !== mangledName) { - return ts.stringContains(withoutAtTypePrefix, mangledScopedPackageSeparator) ? - "@" + withoutAtTypePrefix.replace(mangledScopedPackageSeparator, ts.directorySeparator) : - withoutAtTypePrefix; + return getUnmangledNameForScopedPackage(withoutAtTypePrefix); } return mangledName; } ts.getPackageNameFromAtTypesDirectory = getPackageNameFromAtTypesDirectory; + function getUnmangledNameForScopedPackage(typesPackageName) { + return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ? + "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) : + typesPackageName; + } + ts.getUnmangledNameForScopedPackage = getUnmangledNameForScopedPackage; function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, traceEnabled, host) { var result = cache && cache.get(containingDirectory); if (result) { diff --git a/lib/zh-CN/diagnosticMessages.generated.json b/lib/zh-CN/diagnosticMessages.generated.json index d134b997789..1fb25de397b 100644 --- a/lib/zh-CN/diagnosticMessages.generated.json +++ b/lib/zh-CN/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空间声明必须位于与之合并的类或函数所在的相同文件内。", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空间声明不能位于与之合并的类或函数前", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只允许在命名空间或模块中使用命名空间声明。", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "命名空间样式导入不能调用或构造,并将在运行时导致失败。", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "只允许在函数或构造函数实现中使用参数初始化表达式。", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "不能使用 rest 参数声明参数属性。", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "只允许在构造函数实现中使用参数属性。", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "访问器仅在面向 ECMAScript 5 和更高版本时可用。", "Accessors_must_both_be_abstract_or_non_abstract_2676": "两个取值函数必须都是抽象的或都是非抽象的。", "Add_0_to_existing_import_declaration_from_1_90015": "将“{0}”从“{1}”添加到现有导入声明", + "Add_async_modifier_to_containing_function_90029": "将异步修饰符添加到包含函数", "Add_index_signature_for_property_0_90017": "为属性“{0}”添加索引签名", "Add_missing_super_call_90001": "添加缺失的 \"super()\" 调用", "Add_this_to_unresolved_variable_90008": "向未解析的变量添加 \"this.\"", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引签名参数不能具有可访问性修饰符。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引签名参数不能具有初始化表达式。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引签名参数必须具有类型批注。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引签名参数类型不能为类型别名。请考虑改而编写“[{0}: {1}]:{2}”。", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引签名参数类型不能为联合类型。请考虑改用映射的对象类型。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引签名参数类型必须为 \"string\" 或 \"number\"。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "接口只能扩展具有可选类型参数的标识符/限定名称。", "An_interface_may_only_extend_a_class_or_another_interface_2312": "接口只能扩展类或其他接口。", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "无法导入类型声明文件。请考虑导入“{0}”,而不是“{1}”。", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "无法在块范围声明“{1}”所在的范围内初始化外部范围变量“{0}”。", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "无法调用类型缺少调用签名的表达式。类型“{0}”没有兼容的调用签名。", + "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_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}”。", @@ -246,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含文件,并且无法确定根目录,正在跳过在 \"node_modules\" 文件夹中查找。", "Convert_function_0_to_class_95002": "将函数“{0}”转换为类", "Convert_function_to_an_ES2015_class_95001": "将函数转换为 ES2015 类", + "Convert_to_ES6_module_95017": "转换为 ES6 模块", "Convert_to_default_import_95013": "转换为默认导入", "Corrupted_locale_file_0_6051": "区域设置文件 {0} 已损坏。", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "无法找到模块“{0}”的声明文件。“{1}”隐式拥有 \"any\" 类型。", @@ -310,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "启用类中属性初始化的严格检查。", "Enable_strict_null_checks_6113": "启用严格的 NULL 检查。", "Enable_tracing_of_the_name_resolution_process_6085": "启用名称解析过程的跟踪。", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "通过为所有导入创建命名空间对象来启用 CommonJS 和 ES 模块之间的发出互操作性。表示 \"allowSyntheticDefaultImports\"。", "Enables_experimental_support_for_ES7_async_functions_6068": "对 ES7 异步函数启用实验支持。", "Enables_experimental_support_for_ES7_decorators_6065": "对 ES7 修饰器启用实验支持。", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "对发出修饰器的类型元数据启用实验支持。", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "“{0}”的最长匹配前缀为“{1}”。", "Looking_up_in_node_modules_folder_initial_location_0_6125": "正在在 \"node_modules\" 文件夹中查找,初始位置“{0}”。", "Make_super_call_the_first_statement_in_the_constructor_90002": "在构造函数中,使 \"super()\" 调用第一个语句", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "映射的对象类型隐式地含有 \"any\" 模板类型。", "Member_0_implicitly_has_an_1_type_7008": "成员“{0}”隐式包含类型“{1}”。", "Merge_conflict_marker_encountered_1185": "遇到合并冲突标记。", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "合并声明“{0}”不能包含默认导出声明。请考虑改为添加一个独立的“导出默认 {0}”声明。", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "属性“{0}”没有初始化表达式,且未在构造函数中明确赋值。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "属性“{0}”隐式具有类型 \"any\",因为其 get 访问器缺少返回类型批注。", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "属性“{0}”隐式具有类型 \"any\",因为其 set 访问器缺少参数类型批注。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "类型“{1}”中的属性“{0}”不可分配给基类型“{2}”中的同一属性。", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "类型“{1}”中的属性“{0}”不可分配给类型“{2}”。", "Property_0_is_declared_but_its_value_is_never_read_6138": "已声明属性“{0}”,但从未读取其值。", "Property_0_is_incompatible_with_index_signature_2530": "属性“{0}”与索引签名不兼容。", @@ -637,6 +648,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "在带隐式“any\" 类型的 \"this\" 表达式上引发错误。", "Redirect_output_structure_to_the_directory_6006": "将输出结构重定向到目录。", "Remove_declaration_for_Colon_0_90004": "删除“{0}”的声明", + "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 情况的错误。", "Report_errors_in_js_files_8019": ".js 文件中的报表出错。", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "未终止的模板文本。", "Untyped_function_calls_may_not_accept_type_arguments_2347": "非类型化函数调用不能接受类型参数。", "Unused_label_7028": "未使用的标签。", + "Use_synthetic_default_member_95016": "使用综合的“默认”成员。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "仅 ECMAScript 5 和更高版本支持在 \"for...of\" 语句中使用字符串。", "VERSION_6036": "版本", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "类型“{0}”的值没有与类型“{1}”相同的属性。你是想调用它吗?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "必须初始化 \"const\" 声明。", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "\"const\" 枚举成员初始化表达式的求值结果为非有限值。", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "\"const\" 枚举成员初始化表达式的求值结果为不允许使用的值 \"NaN\"。", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "\"const\" 枚举仅可在属性、索引访问表达式、导入声明的右侧或导出分配中使用。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "\"const\" 枚举仅可在属性、索引访问表达式、导入声明的右侧、导出分配或类型查询中使用。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "在严格模式下,无法对标识符调用 \"delete\"。", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "\"enum declarations\" 只能在 .ts 文件中使用。", "export_can_only_be_used_in_a_ts_file_8003": "\"export=\" 只能在 .ts 文件中使用。", diff --git a/lib/zh-TW/diagnosticMessages.generated.json b/lib/zh-TW/diagnosticMessages.generated.json index fbd1a73857e..fedb82499f4 100644 --- a/lib/zh-TW/diagnosticMessages.generated.json +++ b/lib/zh-TW/diagnosticMessages.generated.json @@ -48,6 +48,7 @@ "A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merg_2433": "命名空間宣告的所在檔案位置,不得與其要合併的類別或函式不同。", "A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged_2434": "命名空間宣告的位置不得先於其要合併的類別或函式。", "A_namespace_declaration_is_only_allowed_in_a_namespace_or_module_1235": "只有命名空間或模組才允許命名空間宣告。", + "A_namespace_style_import_cannot_be_called_or_constructed_and_will_cause_a_failure_at_runtime_7038": "命名空間樣式的匯入無法加以呼叫或建構,而且會導致執行階段失敗。", "A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation_2371": "只有函式或建構函式實作才可使用參數初始設定式。", "A_parameter_property_cannot_be_declared_using_a_rest_parameter_1317": "無法使用剩餘參數宣告參數屬性。", "A_parameter_property_is_only_allowed_in_a_constructor_implementation_2369": "建構函式實作中只可有一個參數屬性。", @@ -92,6 +93,7 @@ "Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher_1056": "只有當目標為 ECMAScript 5 及更高版本時,才可使用存取子。", "Accessors_must_both_be_abstract_or_non_abstract_2676": "存取子必須兩者均為抽象或非抽象。", "Add_0_to_existing_import_declaration_from_1_90015": "從 \"{1}\" 將 '{0}' 新增至現有的匯入宣告", + "Add_async_modifier_to_containing_function_90029": "將 async 修飾詞新增至包含的函式", "Add_index_signature_for_property_0_90017": "為屬性 '{0}' 新增索引簽章", "Add_missing_super_call_90001": "新增遺漏的 'super()' 呼叫", "Add_this_to_unresolved_variable_90008": "將 'this' 新增至未解析的變數", @@ -136,6 +138,8 @@ "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引簽章參數不得有存取範圍修飾詞。", "An_index_signature_parameter_cannot_have_an_initializer_1020": "索引簽章參數不得有初始設定式。", "An_index_signature_parameter_must_have_a_type_annotation_1022": "索引簽章參數必須有類型註釋。", + "An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead_1336": "索引簽章參數類型不能是類型別名。請考慮改為撰寫 '[{0}: {1}]: {2}'。", + "An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead_1337": "索引簽章參數類型不能是等位型別。請考慮改用對應的物件類型。", "An_index_signature_parameter_type_must_be_string_or_number_1023": "索引簽章參數類型必須是 'string' 或 'number'。", "An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments_2499": "介面只能擴充具有選擇性型別引數的識別碼/限定名稱。", "An_interface_may_only_extend_a_class_or_another_interface_2312": "每個介面只可擴充一個類別或另一個介面。", @@ -196,6 +200,9 @@ "Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1_6137": "無法匯入型別宣告檔案。請考慮匯入 '{0}' 而不是 '{1}'。", "Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1_2481": "無法初始化區塊範圍宣告 '{1}' 之同一範圍中的外部範圍變數 '{0}'。", "Cannot_invoke_an_expression_whose_type_lacks_a_call_signature_Type_0_has_no_compatible_call_signatur_2349": "無法叫用類型缺少呼叫簽章的運算式。類型 '{0}' 不含相容的呼叫簽章。", + "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_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}'。", @@ -246,6 +253,7 @@ "Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_mod_6126": "未指定包含檔案,因此無法決定根目錄,而將略過 'node_modules' 中的查閱。", "Convert_function_0_to_class_95002": "將函式 '{0}' 轉換為類別", "Convert_function_to_an_ES2015_class_95001": "將函式轉換為 ES2015 類別", + "Convert_to_ES6_module_95017": "轉換為 ES6 模組", "Convert_to_default_import_95013": "轉換為預設匯入", "Corrupted_locale_file_0_6051": "地區設定檔 {0} 已損毀。", "Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type_7016": "找不到模組 '{0}' 的宣告檔案。'{1}' 隱含具有 'any' 類型。", @@ -310,6 +318,7 @@ "Enable_strict_checking_of_property_initialization_in_classes_6187": "啟用類別中屬性初始化的 strict 檢查。", "Enable_strict_null_checks_6113": "啟用嚴格 null 檢查。", "Enable_tracing_of_the_name_resolution_process_6085": "啟用名稱解析流程的追蹤。", + "Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for__7037": "透過為所有匯入建立命名空間物件,讓 CommonJS 和 ES 模組之間的產出有互通性。意指 'allowSyntheticDefaultImports'。", "Enables_experimental_support_for_ES7_async_functions_6068": "啟用 ES7 非同步函式的實驗支援。", "Enables_experimental_support_for_ES7_decorators_6065": "啟用 ES7 裝飾項目的實驗支援。", "Enables_experimental_support_for_emitting_type_metadata_for_decorators_6066": "啟用實驗支援以發出裝飾項目類型的中繼資料。", @@ -485,6 +494,7 @@ "Longest_matching_prefix_for_0_is_1_6108": "符合 '{0}' 的前置詞最長為 '{1}'。", "Looking_up_in_node_modules_folder_initial_location_0_6125": "目前正在 'node_modules' 資料夾中查詢,初始位置為 '{0}'。", "Make_super_call_the_first_statement_in_the_constructor_90002": "使 'super()' 呼叫成為建構函式中的第一個陳述式", + "Mapped_object_type_implicitly_has_an_any_template_type_7039": "對應的物件類型隱含具有 'any' 範本類型。", "Member_0_implicitly_has_an_1_type_7008": "成員 '{0}' 隱含了 '{1}' 類型。", "Merge_conflict_marker_encountered_1185": "偵測到合併衝突標記。", "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652": "合併宣告 '{0}' 不得包含預設匯出宣告。請考慮改為加入獨立型 'export default {0}' 宣告。", @@ -598,6 +608,7 @@ "Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor_2564": "屬性 '{0}' 沒有初始設定式,且未在建構函式中明確指派。", "Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation_7033": "因為屬性 '{0}' 的 get 存取子沒有傳回類型註釋,致使該屬性意味著類型 'any'。", "Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation_7032": "因為屬性 '{0}' 的 set 存取子沒有參數類型註釋,致使該屬性意味著類型 'any'。", + "Property_0_in_type_1_is_not_assignable_to_the_same_property_in_base_type_2_2416": "類型 '{1}' 中的屬性 '{0}' 無法指派給基底類型 '{2}' 中的相同屬性。", "Property_0_in_type_1_is_not_assignable_to_type_2_2603": "不得將類型 '{1}' 的屬性 '{0}' 指派給類型 '{2}'。", "Property_0_is_declared_but_its_value_is_never_read_6138": "屬性 '{0}' 已宣告但從未讀取其值。", "Property_0_is_incompatible_with_index_signature_2530": "屬性 '{0}' 和索引簽章不相容。", @@ -637,6 +648,7 @@ "Raise_error_on_this_expressions_with_an_implied_any_type_6115": "對具有隱含 'any' 類型的 'this' 運算式引發錯誤。", "Redirect_output_structure_to_the_directory_6006": "將輸出結構重新導向至目錄。", "Remove_declaration_for_Colon_0_90004": "移除 '{0}' 的宣告", + "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 案例的錯誤。", "Report_errors_in_js_files_8019": "報告 .js 檔案中的錯誤。", @@ -861,6 +873,7 @@ "Unterminated_template_literal_1160": "未結束的樣板常值。", "Untyped_function_calls_may_not_accept_type_arguments_2347": "不具類型的函式呼叫無法接受類型引數。", "Unused_label_7028": "未使用的標籤。", + "Use_synthetic_default_member_95016": "使用綜合 'default' 成員。", "Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher_2494": "只有在 ECMAScript 5 及更高版本中,才可在 'for...of' 陳述式中使用字串。", "VERSION_6036": "版本", "Value_of_type_0_has_no_properties_in_common_with_type_1_Did_you_mean_to_call_it_2560": "類型為 '{0}' 的值與類型 '{1}' 沒有任何共通的屬性。確定要呼叫嗎?", @@ -916,7 +929,7 @@ "const_declarations_must_be_initialized_1155": "'const' 宣告必須初始化。", "const_enum_member_initializer_was_evaluated_to_a_non_finite_value_2477": "'const' 列舉成員初始設定式已評估為非有限值。", "const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN_2478": "'const' 列舉成員初始設定式已評估為不允許的值 'NaN'。", - "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列舉只可用於屬性或索引存取運算式中,或者用於匯入宣告或匯出指派的右側。", + "const_enums_can_only_be_used_in_property_or_index_access_expressions_or_the_right_hand_side_of_an_im_2475": "'const' 列舉只可用於屬性或索引存取運算式中,或用於匯入宣告、匯出指派或類型查詢的右側。", "delete_cannot_be_called_on_an_identifier_in_strict_mode_1102": "不得在 strict 模式中對識別碼呼叫 'delete'。", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'enum declarations' 只可用於 .ts 檔案中。", "export_can_only_be_used_in_a_ts_file_8003": "'export=' 只可用於 .ts 檔案中。",