diff --git a/.github/ISSUE_TEMPLATE/Bug_report.md b/.github/ISSUE_TEMPLATE/Bug_report.md index 89da312503a..62647a8b163 100644 --- a/.github/ISSUE_TEMPLATE/Bug_report.md +++ b/.github/ISSUE_TEMPLATE/Bug_report.md @@ -15,8 +15,12 @@ Please help us by doing the following steps before logging an issue: Please fill in the *entire* template below. --> - -**TypeScript Version:** 3.4.0-dev.201xxxxx + +**TypeScript Version:** 3.7.x-dev.201xxxxx **Search Terms:** diff --git a/.gitignore b/.gitignore index 86f344eda49..b5a7c0e59e3 100644 --- a/.gitignore +++ b/.gitignore @@ -61,9 +61,10 @@ internal/ **/.DS_Store .settings **/.vs -**/.vscode +**/.vscode/* !**/.vscode/tasks.json -!**/.vscode/settings.json +!**/.vscode/settings.template.json +!**/.vscode/launch.template.json !**/.vscode/extensions.json !tests/cases/projects/projectOption/**/node_modules !tests/cases/projects/NodeModulesSearch/**/* diff --git a/.vscode/launch.template.json b/.vscode/launch.template.json new file mode 100644 index 00000000000..ede5febb3bf --- /dev/null +++ b/.vscode/launch.template.json @@ -0,0 +1,60 @@ +/* + + Copy this file into '.vscode/launch.json' or merge its + contents into your existing configurations. + + If you want to remove the errors in comments for all JSON + files, add this to your settings in ~/.vscode/User/settings.json + + "files.associations": { + "*.json": "jsonc" + }, + +*/ + +{ + // Use IntelliSense to learn about possible attributes. + // Hover to view descriptions of existing attributes. + // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 + "version": "0.2.0", + "configurations": [ + { + "type": "node", + "protocol": "inspector", + "request": "launch", + "name": "Mocha Tests (currently opened test)", + "runtimeArgs": ["--nolazy"], + "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha", + "args": [ + "-u", + "bdd", + "--no-timeouts", + "--colors", + "built/local/run.js", + "-f", + // You can change this to be the name of a specific test file (without the file extension) + // to consistently launch the same test + "${fileBasenameNoExtension}", + "--skip-percent", + "0" + ], + "env": { + "NODE_ENV": "testing" + }, + "sourceMaps": true, + "smartStep": true, + "preLaunchTask": "tests", + "console": "integratedTerminal", + "outFiles": [ + "${workspaceRoot}/built/local/run.js" + ] + }, + { + // See: https://github.com/microsoft/TypeScript/wiki/Debugging-Language-Service-in-VS-Code + "type": "node", + "request": "attach", + "name": "Attach to VS Code TS Server via Port", + "processId": "${command:PickProcess}" + } + ] +} diff --git a/.vscode/settings.json b/.vscode/settings.json deleted file mode 100644 index 14f7984e7e9..00000000000 --- a/.vscode/settings.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "eslint.validate": [ - { - "language": "typescript", - "autoFix": true - } - ], - "eslint.options": { - "rulePaths": ["./scripts/eslint/built/rules/"], - "ext": [".ts"] - } -} \ No newline at end of file diff --git a/.vscode/settings.template.json b/.vscode/settings.template.json new file mode 100644 index 00000000000..1806a93ecbc --- /dev/null +++ b/.vscode/settings.template.json @@ -0,0 +1,19 @@ +// Rename this file 'settings.json' or merge its +// contents into your existing settings. +{ + "eslint.validate": [ + { + "language": "typescript", + "autoFix": true + } + ], + "eslint.options": { + "rulePaths": ["./scripts/eslint/built/rules/"], + "ext": [".ts"] + }, + // To use the last-known-good (LKG) compiler version: + // "typescript.tsdk": "lib" + + // To use the locally built compiler, after 'npm run build': + // "typescript.tsdk": "built/local" +} \ No newline at end of file diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4b804414ab5..dda3ab28a7b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -160,6 +160,8 @@ You can debug with VS Code or Node instead with `gulp runtests --inspect=true`: gulp runtests --tests=2dArrays --inspect=true ``` +You can also use the [provided VS Code launch configuration](./.vscode/launch.template.json) to launch a debug session for an open test file. Rename the file 'launch.json', open the test file of interest, and launch the debugger from the debug panel (or press F5). + ## Adding a Test To add a new test case, simply place a `.ts` file in `tests\cases\compiler` containing code that exemplifies the bugfix or change you are making. diff --git a/Gulpfile.js b/Gulpfile.js index b5ed366ee64..4c40a73cdba 100644 --- a/Gulpfile.js +++ b/Gulpfile.js @@ -90,8 +90,18 @@ const localize = async () => { } }; +const buildShims = () => buildProject("src/shims"); +const cleanShims = () => cleanProject("src/shims"); +cleanTasks.push(cleanShims); + +const buildDebugTools = () => buildProject("src/debug"); +const cleanDebugTools = () => cleanProject("src/debug"); +cleanTasks.push(cleanDebugTools); + +const buildShimsAndTools = parallel(buildShims, buildDebugTools); + // Pre-build steps when targeting the LKG compiler -const lkgPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics)); +const lkgPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildShimsAndTools)); const buildTsc = () => buildProject("src/tsc"); task("tsc", series(lkgPreBuild, buildTsc)); @@ -107,7 +117,7 @@ task("watch-tsc", series(lkgPreBuild, parallel(watchLib, watchDiagnostics, watch task("watch-tsc").description = "Watch for changes and rebuild the command-line compiler only."; // Pre-build steps when targeting the built/local compiler. -const localPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildTsc)); +const localPreBuild = parallel(generateLibs, series(buildScripts, generateDiagnostics, buildShimsAndTools, buildTsc)); // Pre-build steps to use based on supplied options. const preBuild = cmdLineOptions.lkg ? lkgPreBuild : localPreBuild; diff --git a/README.md b/README.md index c1bf05b11b6..459cebe95b9 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,7 @@ with any additional questions or comments. ## Documentation -* [Quick tutorial](https://www.typescriptlang.org/docs/tutorial.html) +* [TypeScript in 5 minutes](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes.html) * [Programming handbook](https://www.typescriptlang.org/docs/handbook/basic-types.html) * [Language specification](https://github.com/microsoft/TypeScript/blob/master/doc/spec.md) * [Homepage](https://www.typescriptlang.org/) diff --git a/lib/cs/diagnosticMessages.generated.json b/lib/cs/diagnosticMessages.generated.json index 32a067f4fe8..fabd59da8cd 100644 --- a/lib/cs/diagnosticMessages.generated.json +++ b/lib/cs/diagnosticMessages.generated.json @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Implementace funkce chybí nebo nenásleduje hned po deklaraci.", "Function_implementation_name_must_be_0_2389": "Název implementace funkce musí být {0}.", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Funkce implicitně obsahuje návratový typ any, protože neobsahuje anotaci návratového typu a odkazuje se na ni přímo nebo nepřímo v jednom z jejích návratových výrazů.", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový návratový příkaz a návratový typ neobsahuje undefined.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Ve funkci chybí koncový příkaz return a návratový typ neobsahuje undefined.", "Function_overload_must_be_static_2387": "Přetížení funkce musí být statické.", "Function_overload_must_not_be_static_2388": "Přetížení funkce nesmí být statické.", "Generate_get_and_set_accessors_95046": "Generovat přístupové objekty get a set", diff --git a/lib/de/diagnosticMessages.generated.json b/lib/de/diagnosticMessages.generated.json index f7bf53b6755..d010e950339 100644 --- a/lib/de/diagnosticMessages.generated.json +++ b/lib/de/diagnosticMessages.generated.json @@ -1032,7 +1032,7 @@ "await_expression_is_only_allowed_within_an_async_function_1308": "Der Ausdruck \"await\" ist nur in einer asynchronen Funktion zulässig.", "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "await-Ausdrücke dürfen nicht in einem Parameterinitialisierer verwendet werden.", "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "Die Option \"baseUrl\" ist auf \"{0}\" festgelegt. Dieser Wert wird verwendet, um den nicht relativen Modulnamen \"{1}\" aufzulösen.", - "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" kann nur in einer Objektliteraleigenschaft innerhalb eines Destrukturierungsauftrags verwendet werden.", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "\"=\" kann nur in einer Objektliteraleigenschaft innerhalb eines Destrukturierungszuweisung verwendet werden.", "case_or_default_expected_1130": "\"case\" oder \"default\" wurde erwartet.", "class_expressions_are_not_currently_supported_9003": "class-Ausdrücke werden zurzeit nicht unterstützt.", "const_declarations_can_only_be_declared_inside_a_block_1156": "const-Deklarationen können nur innerhalb eines Blocks deklariert werden.", diff --git a/lib/es/diagnosticMessages.generated.json b/lib/es/diagnosticMessages.generated.json index 52840b1208e..c0ce6ef5b8d 100644 --- a/lib/es/diagnosticMessages.generated.json +++ b/lib/es/diagnosticMessages.generated.json @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Falta la implementación de función o no sigue inmediatamente a la declaración.", "Function_implementation_name_must_be_0_2389": "El nombre de la implementación de función debe ser '{0}'.", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "La función tiene el tipo de valor devuelto \"any\" implícitamente porque no tiene una anotación de tipo de valor devuelto y se hace referencia a ella directa o indirectamente en una de sus expresiones return.", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción return final en la función y el tipo de valor devuelto no incluye 'undefined'.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Falta la instrucción \"return\" final en la función y el tipo de valor devuelto no incluye 'undefined'.", "Function_overload_must_be_static_2387": "La sobrecarga de función debe ser estática.", "Function_overload_must_not_be_static_2388": "La sobrecarga de función no debe ser estática.", "Generate_get_and_set_accessors_95046": "Generar los descriptores de acceso \"get\" y \"set\"", @@ -453,7 +453,7 @@ "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Los generadores solo están disponibles cuando el destino es ECMAScript 2015 o una versión posterior.", "Generic_type_0_requires_1_type_argument_s_2314": "El tipo genérico '{0}' requiere los siguientes argumentos de tipo: {1}.", "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "El tipo genérico \"{0}\" requiere entre {1} y {2} argumentos de tipo.", - "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creación de instancias de tipo genérico es excesivamente profunda y posiblemente infinita.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "La creación de una instancia de tipo genérico es excesivamente profunda y posiblemente infinita.", "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Los descriptores de acceso de captador y establecedor no se corresponden respecto a la visibilidad.", "Global_module_exports_may_only_appear_at_top_level_1316": "Las exportaciones de módulos globales solo pueden aparecer en el nivel superior.", "Global_module_exports_may_only_appear_in_declaration_files_1315": "Las exportaciones de módulos globales solo pueden aparecer en archivos de declaración.", diff --git a/lib/fr/diagnosticMessages.generated.json b/lib/fr/diagnosticMessages.generated.json index 1699b44df8b..7a84aae4982 100644 --- a/lib/fr/diagnosticMessages.generated.json +++ b/lib/fr/diagnosticMessages.generated.json @@ -142,7 +142,7 @@ "An_async_iterator_must_have_a_next_method_2519": "Un itérateur asynchrone doit comporter une méthode 'next()'.", "An_element_access_expression_should_take_an_argument_1011": "Une expression d'accès à un élément doit accepter un argument.", "An_enum_member_cannot_have_a_numeric_name_2452": "Un membre enum ne peut pas avoir un nom numérique.", - "An_export_assignment_can_only_be_used_in_a_module_1231": "Une attribution d'exportation peut uniquement être utilisée dans un module.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Une affectation d'exportation peut uniquement être utilisée dans un module.", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Impossible d'utiliser une assignation d'exportation dans un module comportant d'autres éléments exportés.", "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Une affectation d'exportation ne peut pas être utilisée dans un espace de noms.", "An_export_assignment_cannot_have_modifiers_1120": "Une assignation d'exportation ne peut pas avoir de modificateurs.", @@ -594,7 +594,7 @@ "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Aucune entrée dans le fichier config '{0}'. Les chemins 'include' spécifiés étaient '{1}' et les chemins 'exclude' étaient '{2}'.", "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "La classe non abstraite '{0}' n'implémente pas le membre abstrait '{1}' hérité de la classe '{2}'.", "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "L'expression de classe non abstraite '{0}' n'implémente pas le membre abstrait hérité '{0}' de la classe '{1}'.", - "Not_all_code_paths_return_a_value_7030": "Les chemins de code ne retournent pas tous une valeur.", + "Not_all_code_paths_return_a_value_7030": "Les chemins du code ne retournent pas tous une valeur.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Impossible d'assigner le type d'index numérique '{0}' au type d'index de chaîne '{1}'.", "Numeric_separators_are_not_allowed_here_6188": "Les séparateurs numériques ne sont pas autorisés ici.", "Object_is_of_type_unknown_2571": "L'objet est de type 'unknown'.", @@ -745,7 +745,7 @@ "Remove_unused_label_95053": "Supprimer l'étiquette inutilisée", "Remove_variable_statement_90010": "Supprimer l'instruction de variable", "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_error_when_not_all_code_paths_in_function_return_a_value_6075": "Signalez une erreur quand les chemins du 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.", "Report_errors_on_unused_locals_6134": "Signaler les erreurs sur les variables locales inutilisées.", diff --git a/lib/ja/diagnosticMessages.generated.json b/lib/ja/diagnosticMessages.generated.json index d3029982ca6..751357dbc01 100644 --- a/lib/ja/diagnosticMessages.generated.json +++ b/lib/ja/diagnosticMessages.generated.json @@ -130,7 +130,7 @@ "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "'--isolatedModules' フラグが指定されている場合、アンビエント const 列挙型は使用できません。", "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "アンビエント モジュール宣言では、相対モジュール名を指定できません。", "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "アンビエント モジュールを、他のモジュールまたは名前空間内の入れ子にすることはできません。", - "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を割り当てることはできません。", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "AMD モジュールに複数の名前を代入することはできません。", "An_abstract_accessor_cannot_have_an_implementation_1318": "抽象アクセサーに実装を含めることはできません。", "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "環境コンテキストではアクセサーは宣言できません。", "An_accessor_cannot_have_type_parameters_1094": "アクセサーに型パラメーターを指定することはできません。", @@ -142,10 +142,10 @@ "An_async_iterator_must_have_a_next_method_2519": "非同期反復子には 'next()' メソッドが必要です。", "An_element_access_expression_should_take_an_argument_1011": "要素アクセス式では、引数を取る必要があります。", "An_enum_member_cannot_have_a_numeric_name_2452": "列挙型メンバーに数値名を含めることはできません。", - "An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの割り当てはモジュールでのみ使用可能です。", - "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの割り当ては、エクスポートされた他の要素を含むモジュールでは使用できません。", - "An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの割り当ては、名前空間では使用できません。", - "An_export_assignment_cannot_have_modifiers_1120": "エクスポートの割り当てに修飾子を指定することはできません。", + "An_export_assignment_can_only_be_used_in_a_module_1231": "エクスポートの代入はモジュールでのみ使用可能です。", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "エクスポートの代入は、エクスポートされた他の要素を含むモジュールでは使用できません。", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "エクスポートの代入は、名前空間では使用できません。", + "An_export_assignment_cannot_have_modifiers_1120": "エクスポートの代入に修飾子を指定することはできません。", "An_export_declaration_can_only_be_used_in_a_module_1233": "エクスポート宣言はモジュールでのみ使用可能です。", "An_export_declaration_cannot_have_modifiers_1193": "エクスポート宣言に修飾子を指定することはできません。", "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "拡張された Unicode エスケープ値は 0x0 と 0x10FFFF の間 (両端を含む) でなければなりません。", @@ -389,8 +389,8 @@ "Experimental_Options_6177": "試験的なオプション", "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "デコレーターの実験的なサポートは将来のリリースで変更になる可能性がある機能です。'experimentalDecorators' オプションを設定してこの警告を削除します。", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "明示的に指定されたモジュール解決の種類 '{0}'。", - "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート割り当てを使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。", - "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "割り当てのエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。", + "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "ECMAScript モジュールを対象にする場合は、エクスポート代入を使用できません。代わりに 'export default' または別のモジュール書式の使用をご検討ください。", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "代入のエクスポートは、'--module' フラグが 'system' の場合にはサポートされません。", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "エクスポート宣言が、'{0}' のエクスポートされた宣言と競合しています。", "Export_declarations_are_not_permitted_in_a_namespace_1194": "エクスポート宣言は名前空間でサポートされません。", "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "エクスポートされた外部パッケージの型指定のファイル '{0}' はモジュールではありません。パッケージ定義を更新する場合は、パッケージの作成者にお問い合わせください。", @@ -399,7 +399,7 @@ "Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named_4023": "エクスポートされた変数 '{0}' が外部モジュール {2} の名前 '{1}' を持っているか使用していますが、名前を指定することはできません。", "Exported_variable_0_has_or_is_using_name_1_from_private_module_2_4024": "エクスポートされた変数 '{0}' がプライベート モジュール '{2}' の名前 '{1}' を持っているか、使用しています。", "Exported_variable_0_has_or_is_using_private_name_1_4025": "エクスポートされた変数 '{0}' がプライベート名 '{1}' を持っているか、使用しています。", - "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの割り当てはモジュールの拡張では許可されていません。", + "Exports_and_export_assignments_are_not_permitted_in_module_augmentations_2666": "エクスポートとエクスポートの代入はモジュールの拡張では許可されていません。", "Expression_expected_1109": "式が必要です。", "Expression_or_comma_expected_1137": "式またはコンマが必要です。", "Expression_resolves_to_super_that_compiler_uses_to_capture_base_class_reference_2402": "式は、コンパイラが基底クラスの参照をキャプチャするために使用する '_super' に解決されます。", @@ -473,7 +473,7 @@ "Implement_interface_0_90006": "インターフェイス '{0}' を実装する", "Implements_clause_of_exported_class_0_has_or_is_using_private_name_1_4019": "エクスポートされたクラス '{0}' の Implements 句がプライベート名 '{1}' を持っているか、使用しています。", "Import_0_from_module_1_90013": "モジュール \"{1}\" から '{0}' をインポートする", - "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート割り当てを使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。", + "Import_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_import_Asterisk_as_1202": "ECMAScript モジュールを対象にする場合は、インポート代入を使用できません。代わりに 'import * as ns from \"mod\"'、'import {a} from \"mod\"'、'import d from \"mod\"' などのモジュール書式の使用をご検討ください。", "Import_declaration_0_is_using_private_name_1_4000": "インポート宣言 '{0}' がプライベート名 '{1}' を使用しています。", "Import_declaration_conflicts_with_local_declaration_of_0_2440": "インポート宣言が、'{0}' のローカル宣言と競合しています。", "Import_declarations_in_a_namespace_cannot_reference_a_module_1147": "名前空間内のインポート宣言は、モジュールを参照できません。", @@ -536,7 +536,7 @@ "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 要素に同じ名前の複数の属性を指定することはできません。", "JSX_expressions_must_have_one_parent_element_2657": "JSX 式には 1 つの親要素が必要です。", "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX フラグメントには対応する終了タグがありません。", - "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ プラグマの使用時にサポートされていません", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "JSX フラグメントはインライン JSX ファクトリ pragma の使用時にサポートされていません", "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "--jsxFactory を使う場合、JSX フラグメントはサポートされません", "JSX_spread_child_must_be_an_array_type_2609": "JSX スプレッドの子は、配列型でなければなりません。", "Jump_target_cannot_cross_function_boundary_1107": "ジャンプ先は関数の境界を越えることはできません。", @@ -714,7 +714,7 @@ "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "エクスポートされたインターフェイスのプロパティ '{0}' が、プライベート名 '{1}' を持っているか、使用しています。", "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "型 '{1}' のプロパティ '{0}' を数値インデックス型 '{2}' に割り当てることはできません。", "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "型 '{1}' のプロパティ '{0}' を文字列インデックス型 '{2}' に割り当てることはできません。", - "Property_assignment_expected_1136": "プロパティの割り当てが必要です。", + "Property_assignment_expected_1136": "プロパティの代入が必要です。", "Property_destructuring_pattern_expected_1180": "プロパティの非構造化パターンが必要です。", "Property_or_signature_expected_1131": "プロパティまたはシグネチャが必要です。", "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "プロパティ値には、文字列リテラル、数値リテラル、'true'、'false'、'null'、オブジェクト リテラルまたは配列リテラルのみ使用できます。", @@ -850,7 +850,7 @@ "The_character_set_of_the_input_files_6163": "入力ファイルの文字セット。", "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "含まれている関数またはモジュールの本体は、制御フロー解析には大きすぎます。", "The_current_host_does_not_support_the_0_option_5001": "現在のホストは '{0}' オプションをサポートしていません。", - "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの割り当ての式は、環境コンテキストの識別子または修飾名にする必要があります。", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "エクスポートの代入の式は、環境コンテキストの識別子または修飾名にする必要があります。", "The_files_list_in_config_file_0_is_empty_18002": "構成ファイル '{0}' の 'files' リストが空です。", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Promise では、'then' メソッドの最初のパラメーターはコールバックでなければなりません。", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "グローバル型 'JSX.{0}' には複数のプロパティが含まれていない可能性があります。", @@ -882,7 +882,7 @@ "The_right_hand_side_of_an_instanceof_expression_must_be_of_type_any_or_of_a_type_assignable_to_the_F_2359": "instanceof' 式の右辺には、'any' 型、または 'Function' インターフェイス型に割り当てることができる型を指定してください。", "The_specified_path_does_not_exist_Colon_0_5058": "指定されたパスがありません: '{0}'。", "The_target_of_an_assignment_must_be_a_variable_or_a_property_access_2541": "代入式のターゲットは、変数またはプロパティ アクセスである必要があります。", - "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の割り当ての対象は、変数またはプロパティ アクセスである必要があります。", + "The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access_2701": "オブジェクトの残り部分の代入の対象は、変数またはプロパティ アクセスである必要があります。", "The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1_2684": "型 '{0}' の 'this' コンテキストを型 '{1}' のメソッドの 'this' に割り当てることはできません。", "The_this_types_of_each_signature_are_incompatible_2685": "各シグネチャの 'this' 型に互換性がありません。", "The_type_argument_for_type_parameter_0_cannot_be_inferred_from_the_usage_Consider_specifying_the_typ_2453": "型パラメーター '{0}' の型引数を使用法から推論することはできません。型引数を明示的に指定してください。", @@ -1032,14 +1032,14 @@ "await_expression_is_only_allowed_within_an_async_function_1308": "'await' 式は、非同期関数内でのみ使用できます。", "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 式は、パラメーター初期化子では使用できません。", "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' オプションは '{0}' に設定され、この値を使用して非相対モジュール名 '{1}' を解決します。", - "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' は、非構造化割り当て内のオブジェクト リテラル プロパティでのみ使用できます。", + "can_only_be_used_in_an_object_literal_property_inside_a_destructuring_assignment_1312": "'=' は、非構造化代入内のオブジェクト リテラル プロパティでのみ使用できます。", "case_or_default_expected_1130": "'case' または 'default' が必要です。", "class_expressions_are_not_currently_supported_9003": "'class' 式は現在サポートされていません。", "const_declarations_can_only_be_declared_inside_a_block_1156": "'const' 宣言は、ブロック内でのみ宣言できます。", "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' を識別子で呼び出すことはできません。", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "これを削除します - プロジェクト '{0}' は、以前にビルドされているため、最新の状態です", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "'列挙型宣言' を使用できるのは .ts ファイル内のみです。", diff --git a/lib/ko/diagnosticMessages.generated.json b/lib/ko/diagnosticMessages.generated.json index 1f1f563e44c..fb77b68ac67 100644 --- a/lib/ko/diagnosticMessages.generated.json +++ b/lib/ko/diagnosticMessages.generated.json @@ -1067,7 +1067,7 @@ "or_expected_1144": "'{' 또는 ';'이(가) 필요합니다.", "package_json_does_not_have_a_0_field_6100": "'package.json'에는 '{0}' 필드가 없습니다.", "package_json_has_0_field_1_that_references_2_6101": "'package.json'에 '{2}'을(를) 참조하는 '{0}' 필드 '{1}'이(가) 있습니다.", - "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers'는 .ts 파일에서만 사용할 수 있습니다.", + "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'매개 변수 한정자'는 .ts 파일에서만 사용할 수 있습니다.", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 옵션이 지정되었습니다. 모듈 이름 '{0}'과(와) 일치하는 패턴을 찾는 중입니다.", "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 한정자는 속성 선언 또는 인덱스 시그니처에만 나타날 수 있습니다.", "require_call_may_be_converted_to_an_import_80005": "'require' 호출이 가져오기로 변환될 수 있습니다.", diff --git a/lib/lib.dom.d.ts b/lib/lib.dom.d.ts index da1ba2985dc..4217884bca4 100644 --- a/lib/lib.dom.d.ts +++ b/lib/lib.dom.d.ts @@ -9782,7 +9782,7 @@ interface ImageData { declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height?: number): ImageData; }; interface InnerHTML { @@ -19103,7 +19103,7 @@ declare namespace WebAssembly { var Instance: { prototype: Instance; - new(module: Module, importObject?: any): Instance; + new(module: Module, importObject?: Imports): Instance; }; interface LinkError { diff --git a/lib/lib.es5.d.ts b/lib/lib.es5.d.ts index 13bf9bb239e..a9b9f5b0aea 100644 --- a/lib/lib.es5.d.ts +++ b/lib/lib.es5.d.ts @@ -702,8 +702,8 @@ interface Math { /** Returns a pseudorandom number between 0 and 1. */ random(): number; /** - * Returns a supplied numeric expression rounded to the nearest number. - * @param x The value to be rounded to the nearest number. + * Returns a supplied numeric expression rounded to the nearest integer. + * @param x The value to be rounded to the nearest integer. */ round(x: number): number; /** @@ -893,12 +893,12 @@ interface DateConstructor { /** * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. - * @param month The month as an number between 0 and 11 (January to December). - * @param date The date as an number between 1 and 31. - * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. - * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. - * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. - * @param ms An number from 0 to 999 that specifies the milliseconds. + * @param month The month as a number between 0 and 11 (January to December). + * @param date The date as a number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. + * @param ms A number from 0 to 999 that specifies the milliseconds. */ UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; now(): number; diff --git a/lib/lib.webworker.d.ts b/lib/lib.webworker.d.ts index 57e9b28b531..efc1de2e994 100644 --- a/lib/lib.webworker.d.ts +++ b/lib/lib.webworker.d.ts @@ -2222,7 +2222,7 @@ interface ImageData { declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height?: number): ImageData; }; /** This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties. */ @@ -5629,7 +5629,7 @@ declare namespace WebAssembly { var Instance: { prototype: Instance; - new(module: Module, importObject?: any): Instance; + new(module: Module, importObject?: Imports): Instance; }; interface Memory { diff --git a/lib/pl/diagnosticMessages.generated.json b/lib/pl/diagnosticMessages.generated.json index 9d219542c86..e625476e041 100644 --- a/lib/pl/diagnosticMessages.generated.json +++ b/lib/pl/diagnosticMessages.generated.json @@ -30,7 +30,7 @@ "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Dekorator może dekorować jedynie implementację metody, a nie przeciążenie.", "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Klauzula „default” nie może występować więcej niż raz w instrukcji „switch”.", "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Eksport domyślny może być używany tylko w module w stylu języka ECMAScript.", - "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Asercja określonego przydziału „!” nie jest dozwolona w tym kontekście.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Asercja określonego przypisania „!” nie jest dozwolona w tym kontekście.", "A_destructuring_declaration_must_have_an_initializer_1182": "Deklaracja usuwająca strukturę musi mieć inicjator.", "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Wywołanie dynamicznego importowania w wersji ES5/ES3 wymaga konstruktora „Promise”. Upewnij się, że masz deklarację dla konstruktora „Promise”, lub uwzględnij wartość „ES2015” w opcji „--lib”.", "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Wywołanie dynamicznego importowania zwraca element „Promise”. Upewnij się, że masz deklarację elementu „Promise” lub uwzględnij wartość „ES2015” w opcji „--lib”.", @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Brak implementacji funkcji lub nie występuje ona bezpośrednio po deklaracji.", "Function_implementation_name_must_be_0_2389": "Implementacja funkcji musi mieć nazwę „{0}”.", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Dla funkcji niejawnie określono zwracany typ „any”, ponieważ nie zawiera ona adnotacji zwracanego typu i jest przywoływana bezpośrednio lub pośrednio w jednym z jej zwracanych wyrażeń.", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Funkcja nie zawiera końcowej instrukcji „return”, a zwracany typ nie obejmuje wartości „undefined”.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "Funkcja nie zawiera końcowej instrukcji return, a zwracany typ nie obejmuje wartości „undefined”.", "Function_overload_must_be_static_2387": "Przeciążenie funkcji musi być statyczne.", "Function_overload_must_not_be_static_2388": "Przeciążenie funkcji nie może być statyczne.", "Generate_get_and_set_accessors_95046": "Generuj metody dostępu „get” i „set”.", @@ -594,7 +594,7 @@ "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Nie można znaleźć danych wejściowych w pliku konfiguracji „{0}”. Określone ścieżki „include” to „{1}”, a „exclude” to „{2}”.", "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Klasa nieabstrakcyjna „{0}” nie implementuje odziedziczonej abstrakcyjnej składowej „{1}” z klasy „{2}”.", "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Wyrażenie klasy nieabstrakcyjnej nie implementuje odziedziczonej abstrakcyjnej składowej „{0}” z klasy „{1}”.", - "Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki kodu zwracają wartość.", + "Not_all_code_paths_return_a_value_7030": "Nie wszystkie ścieżki w kodzie zwracają wartość.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Nie można przypisać typu indeksu numerycznego „{0}” do typu indeksu ciągu „{1}”.", "Numeric_separators_are_not_allowed_here_6188": "Separatory liczbowe nie są dozwolone w tym miejscu.", "Object_is_of_type_unknown_2571": "Obiekt jest typu „nieznany”.", @@ -745,7 +745,7 @@ "Remove_unused_label_95053": "Usuń nieużywaną etykietę", "Remove_variable_statement_90010": "Usuń instrukcję zmiennej", "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_error_when_not_all_code_paths_in_function_return_a_value_6075": "Zgłoś błąd, gdy nie wszystkie ścieżki w kodzie 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.", "Report_errors_on_unused_locals_6134": "Raportuj błędy dla nieużywanych elementów lokalnych.", diff --git a/lib/protocol.d.ts b/lib/protocol.d.ts index def3c67bdf0..1747e0f9889 100644 --- a/lib/protocol.d.ts +++ b/lib/protocol.d.ts @@ -652,9 +652,11 @@ declare namespace ts.server.protocol { interface DefinitionResponse extends Response { body?: FileSpanWithContext[]; } - interface DefinitionInfoAndBoundSpanReponse extends Response { + interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; } + /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ + type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; /** * Definition response message. Gives text range for definition. */ @@ -2317,6 +2319,12 @@ declare namespace ts.server.protocol { * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. */ readonly includeCompletionsWithInsertText?: boolean; + /** + * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled, + * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined + * values, with insertion text to replace preceding `.` tokens with `?.`. + */ + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; readonly lazyConfiguredProjectsFromExternalProject?: boolean; diff --git a/lib/pt-br/diagnosticMessages.generated.json b/lib/pt-br/diagnosticMessages.generated.json index de74fa7bdcd..a1623b58108 100644 --- a/lib/pt-br/diagnosticMessages.generated.json +++ b/lib/pt-br/diagnosticMessages.generated.json @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "A implementação da função está ausente ou não está imediatamente depois da declaração.", "Function_implementation_name_must_be_0_2389": "O nome da implementação de função deve ser '{0}'.", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "A função tem o tipo de retorno 'any', de forma implícita, porque ela não tem uma anotação de tipo de retorno e é referenciada direta ou indiretamente em uma das suas expressões de retorno.", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "A função não tem a instrução de retorno final e o tipo de retorno não inclui 'undefined'.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "A função não tem a instrução return final e o tipo de retorno não inclui 'undefined'.", "Function_overload_must_be_static_2387": "A sobrecarga de função deve ser estática.", "Function_overload_must_not_be_static_2388": "A sobrecarga de função não deve ser estática.", "Generate_get_and_set_accessors_95046": "Gerar acessadores 'get' e 'set'", diff --git a/lib/ru/diagnosticMessages.generated.json b/lib/ru/diagnosticMessages.generated.json index 468fd47b888..f66fa953ac1 100644 --- a/lib/ru/diagnosticMessages.generated.json +++ b/lib/ru/diagnosticMessages.generated.json @@ -30,7 +30,7 @@ "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "Декоратор может только декорировать реализацию метода, а не перегрузку.", "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "Предложение default не может повторяться в операторе switch.", "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "Экспорт по умолчанию можно использовать только в модуле в стиле ECMAScript.", - "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Утверждение определенного присваивания \"!\" запрещено в этом контексте.", + "A_definite_assignment_assertion_is_not_permitted_in_this_context_1255": "Утверждение определенного назначения \"!\" запрещено в этом контексте.", "A_destructuring_declaration_must_have_an_initializer_1182": "Объявление деструктурирования должно включать инициализатор.", "A_dynamic_import_call_in_ES5_SlashES3_requires_the_Promise_constructor_Make_sure_you_have_a_declarat_2712": "Для вызова динамического импорта в ES5/ES3 требуется конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".", "A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES20_2711": "Вызов динамического импорта возвращает конструктор \"Promise\". Объявите конструктор \"Promise\" или включите \"ES2015\" в параметр \"--lib\".", @@ -103,8 +103,8 @@ "Add_all_missing_super_calls_95039": "Добавить все отсутствующие вызовы super", "Add_async_modifier_to_containing_function_90029": "Добавьте модификатор async в содержащую функцию", "Add_braces_to_arrow_function_95059": "Добавить скобки в стрелочную функцию", - "Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного присваивания к свойству \"{0}\"", - "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного присваивания ко всем неинициализированным свойствам", + "Add_definite_assignment_assertion_to_property_0_95020": "Добавить утверждение определенного назначения к свойству \"{0}\"", + "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "Добавить утверждения определенного назначения ко всем неинициализированным свойствам", "Add_index_signature_for_property_0_90017": "Добавьте сигнатуру индекса для свойства \"{0}\"", "Add_initializer_to_property_0_95019": "Добавить инициализатор к свойству \"{0}\"", "Add_initializers_to_all_uninitialized_properties_95027": "Добавить инициализаторы ко всем неинициализированным свойствам", @@ -130,7 +130,7 @@ "Ambient_const_enums_are_not_allowed_when_the_isolatedModules_flag_is_provided_1209": "Перечисление внешних констант не разрешено, если задан флаг \"--isolatedModules\".", "Ambient_module_declaration_cannot_specify_relative_module_name_2436": "Объявление окружающего модуля не может содержать относительное имя модуля.", "Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces_2435": "Внешний модуль не может быть вложен в другие модули или пространства имен.", - "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Модуль AMD не может иметь несколько присваиваний имен.", + "An_AMD_module_cannot_have_multiple_name_assignments_2458": "Модуль AMD не может иметь несколько назначений имен.", "An_abstract_accessor_cannot_have_an_implementation_1318": "У абстрактного метода доступа не может быть реализации.", "An_accessor_cannot_be_declared_in_an_ambient_context_1086": "Метод доступа нельзя объявить в окружающем контексте.", "An_accessor_cannot_have_type_parameters_1094": "Метод доступа не может иметь параметры типа.", @@ -142,10 +142,10 @@ "An_async_iterator_must_have_a_next_method_2519": "В асинхронном итераторе должен быть метод next().", "An_element_access_expression_should_take_an_argument_1011": "Выражение доступа к элементу должно принимать аргумент.", "An_enum_member_cannot_have_a_numeric_name_2452": "Имя элемента перечисления не может быть числовым.", - "An_export_assignment_can_only_be_used_in_a_module_1231": "Присваивание экспорта может быть использовано только в модуле.", - "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Присваивание экспорта нельзя использовать в модуле с другими экспортированными элементами.", - "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Присваивание экспорта нельзя использовать в пространстве имен.", - "An_export_assignment_cannot_have_modifiers_1120": "Присваивание экспорта не может иметь модификаторы.", + "An_export_assignment_can_only_be_used_in_a_module_1231": "Назначение экспорта может быть использовано только в модуле.", + "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "Назначение экспорта нельзя использовать в модуле с другими экспортированными элементами.", + "An_export_assignment_cannot_be_used_in_a_namespace_1063": "Назначение экспорта нельзя использовать в пространстве имен.", + "An_export_assignment_cannot_have_modifiers_1120": "Назначение экспорта не может иметь модификаторы.", "An_export_declaration_can_only_be_used_in_a_module_1233": "Объявление экспорта может быть использовано только в модуле.", "An_export_declaration_cannot_have_modifiers_1193": "Объявление экспорта не может иметь модификаторы.", "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "Расширенное escape-значение в Юникоде должно быть в пределах от 0x0 до 0x10FFFF включительно.", @@ -390,7 +390,7 @@ "Experimental_support_for_decorators_is_a_feature_that_is_subject_to_change_in_a_future_release_Set_t_1219": "Экспериментальная поддержка для декораторов — это функция, которая будет изменена в будущем выпуске. Задайте параметр experimentalDecorators, чтобы удалить это предупреждение.", "Explicitly_specified_module_resolution_kind_Colon_0_6087": "Явно указанный тип разрешения модуля: \"{0}\".", "Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or__1203": "Назначение экспорта невозможно использовать при разработке для модулей ECMAScript. Попробуйте использовать \"export default\" или другой формат модуля.", - "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Присваивание экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".", + "Export_assignment_is_not_supported_when_module_flag_is_system_1218": "Назначение экспорта не поддерживается, если флаг \"--module\" имеет значение \"system\".", "Export_declaration_conflicts_with_exported_declaration_of_0_2484": "Объявление экспорта конфликтует с экспортированным объявлением \"{0}\".", "Export_declarations_are_not_permitted_in_a_namespace_1194": "Объявления экспорта не разрешены в пространстве имен.", "Exported_external_package_typings_file_0_is_not_a_module_Please_contact_the_package_author_to_update_2656": "Файл экспортированных внешних типизаций пакета \"{0}\" не является модулем. Обратитесь к автору пакета для обновления определения пакета.", @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "Реализация функции отсутствует либо не идет сразу после объявления.", "Function_implementation_name_must_be_0_2389": "Имя реализации функции должно иметь значение \"{0}\".", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "Функция неявно имеет тип возвращаемого значения any, так как у нее нет заметки с типом возвращаемого значения, а также на нее прямо или косвенно указывает ссылка в одном из ее выражений \"return\".", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "В функции отсутствует завершающий оператор возвращаемого значения, а тип возвращаемого значения не включает undefined.", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "В функции отсутствует завершающий оператор return, а тип возвращаемого значения не включает \"undefined\".", "Function_overload_must_be_static_2387": "Перегрузка функции должна быть статической.", "Function_overload_must_not_be_static_2388": "Перегрузка функции не должна быть статической.", "Generate_get_and_set_accessors_95046": "Создать методы доступа get и set", @@ -594,7 +594,7 @@ "No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2_18003": "Не удалось найти входные данные в файле конфигурации \"{0}\". Указанные пути \"include\": \"{1}\", пути \"exclude\": \"{2}\".", "Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2_2515": "Класс \"{0}\", не являющийся абстрактным, не реализует наследуемый абстрактный элемент \"{1}\" класса \"{2}\".", "Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1_2653": "Выражение неабстрактного класса не реализует унаследованный абстрактный элемент \"{0}\" класса \"{1}\".", - "Not_all_code_paths_return_a_value_7030": "Не все пути кода возвращают значение.", + "Not_all_code_paths_return_a_value_7030": "Не все пути к коду возвращают значение.", "Numeric_index_type_0_is_not_assignable_to_string_index_type_1_2413": "Тип числового индекса \"{0}\" нельзя назначить типу строкового индекса \"{1}\".", "Numeric_separators_are_not_allowed_here_6188": "Числовые разделители здесь запрещены.", "Object_is_of_type_unknown_2571": "Объект имеет тип \"Неизвестный\".", @@ -714,7 +714,7 @@ "Property_0_of_exported_interface_has_or_is_using_private_name_1_4033": "Свойство \"{0}\" экспортированного интерфейса имеет или использует закрытое имя \"{1}\".", "Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2_2412": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу числового индекса \"{2}\".", "Property_0_of_type_1_is_not_assignable_to_string_index_type_2_2411": "Свойство \"{0}\" типа \"{1}\" нельзя назначить типу строкового индекса \"{2}\".", - "Property_assignment_expected_1136": "Ожидалось присваивание свойства.", + "Property_assignment_expected_1136": "Ожидалось назначение свойства.", "Property_destructuring_pattern_expected_1180": "Ожидался шаблон деструктурирования свойства.", "Property_or_signature_expected_1131": "Ожидалось свойство или сигнатура.", "Property_value_can_only_be_string_literal_numeric_literal_true_false_null_object_literal_or_array_li_1328": "Значение свойства может быть только строковым или числовым литералом, True, False, Null, объектным литералом либо литералом массива.", @@ -745,7 +745,7 @@ "Remove_unused_label_95053": "Удалить неиспользуемую метку", "Remove_variable_statement_90010": "Удалить оператор с переменной", "Replace_import_with_0_95015": "Замена импорта на \"{0}\".", - "Report_error_when_not_all_code_paths_in_function_return_a_value_6075": "Сообщать об ошибке, если не все пути кода в функции возвращают значение.", + "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-файлах.", "Report_errors_on_unused_locals_6134": "Сообщать об ошибках в неиспользованных локальных переменных.", @@ -850,7 +850,7 @@ "The_character_set_of_the_input_files_6163": "Кодировка входных файлов.", "The_containing_function_or_module_body_is_too_large_for_control_flow_analysis_2563": "Содержащая функция или текст модуля слишком велики для анализа потока управления.", "The_current_host_does_not_support_the_0_option_5001": "Текущий узел не поддерживает параметр \"{0}\".", - "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Выражение присваивания экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.", + "The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context_2714": "Выражение назначения экспорта должно представлять собой идентификатор или полное имя в окружающем контексте.", "The_files_list_in_config_file_0_is_empty_18002": "Список \"files\" в файле конфигурации \"{0}\" пуст.", "The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback_1060": "Первым параметром метода then класса promise должен быть обратный вызов.", "The_global_type_JSX_0_may_not_have_more_than_one_property_2608": "Глобальный тип \"JSX.{0}\" не может иметь больше одного свойства.", @@ -1039,7 +1039,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 с идентификатором в строгом режиме.", "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "удалить это — проект \"{0}\" не требует обновления, так как был собран ранее", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "Объявления перечислений можно использовать только в TS-файле.", diff --git a/lib/tr/diagnosticMessages.generated.json b/lib/tr/diagnosticMessages.generated.json index 892fc74d391..dc52ec079ef 100644 --- a/lib/tr/diagnosticMessages.generated.json +++ b/lib/tr/diagnosticMessages.generated.json @@ -453,7 +453,7 @@ "Generators_are_only_available_when_targeting_ECMAScript_2015_or_higher_1220": "Oluşturucular yalnızca ECMEAScript 2015 veya üstü hedeflenirken kullanılabilir.", "Generic_type_0_requires_1_type_argument_s_2314": "'{0}' genel türü, {1} tür bağımsız değişkenini gerektiriyor.", "Generic_type_0_requires_between_1_and_2_type_arguments_2707": "'{0}' genel türü {1} ile {2} arasında bağımsız değişken gerektirir.", - "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Genel tür oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.", + "Generic_type_instantiation_is_excessively_deep_and_possibly_infinite_2550": "Genel tür örneği oluşturma işlemi, fazla ayrıntılı ve büyük olasılıkla sınırsız.", "Getter_and_setter_accessors_do_not_agree_in_visibility_2379": "Alıcı ve ayarlayıcı erişimcileri görünürlükte anlaşamıyor.", "Global_module_exports_may_only_appear_at_top_level_1316": "Genel modül dışarı aktarmaları yalnızca en üst düzeyde görünebilir.", "Global_module_exports_may_only_appear_in_declaration_files_1315": "Genel modül dışarı aktarmaları yalnızca bildirim dosyalarında görünebilir.", diff --git a/lib/tsc.js b/lib/tsc.js index 4e5a06816c1..f11a650f5cd 100644 --- a/lib/tsc.js +++ b/lib/tsc.js @@ -70,15 +70,21 @@ var ts; ts.version = ts.versionMajorMinor + ".0-beta"; })(ts || (ts = {})); (function (ts) { - ts.emptyArray = []; - function createDictionaryObject() { - var map = Object.create(null); - map.__ = undefined; - delete map.__; - return map; + function tryGetNativeMap() { + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; } + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); function createMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createMap = createMap; function createMapFromEntries(entries) { @@ -91,7 +97,7 @@ var ts; } ts.createMapFromEntries = createMapFromEntries; function createMapFromTemplate(template) { - var map = new ts.MapCtr(); + var map = new ts.Map(); for (var key in template) { if (hasOwnProperty.call(template, key)) { map.set(key, template[key]); @@ -100,121 +106,6 @@ var ts; return map; } ts.createMapFromTemplate = createMapFromTemplate; - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - function shimMap() { - var MapIterator = (function () { - function MapIterator(currentEntry, selector) { - this.currentEntry = currentEntry; - this.selector = selector; - } - MapIterator.prototype.next = function () { - while (this.currentEntry) { - var skipNext = !!this.currentEntry.skipNext; - this.currentEntry = this.currentEntry.nextEntry; - if (!skipNext) { - break; - } - } - if (this.currentEntry) { - return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false }; - } - else { - return { value: undefined, done: true }; - } - }; - return MapIterator; - }()); - return (function () { - function class_1() { - this.data = createDictionaryObject(); - this.size = 0; - this.firstEntry = {}; - this.lastEntry = this.firstEntry; - } - class_1.prototype.get = function (key) { - var entry = this.data[key]; - return entry && entry.value; - }; - class_1.prototype.set = function (key, value) { - if (!this.has(key)) { - this.size++; - var newEntry = { - key: key, - value: value - }; - this.data[key] = newEntry; - var previousLastEntry = this.lastEntry; - previousLastEntry.nextEntry = newEntry; - newEntry.previousEntry = previousLastEntry; - this.lastEntry = newEntry; - } - else { - this.data[key].value = value; - } - return this; - }; - class_1.prototype.has = function (key) { - return key in this.data; - }; - class_1.prototype.delete = function (key) { - if (this.has(key)) { - this.size--; - var entry = this.data[key]; - delete this.data[key]; - var previousEntry = entry.previousEntry; - previousEntry.nextEntry = entry.nextEntry; - if (entry.nextEntry) { - entry.nextEntry.previousEntry = previousEntry; - } - if (this.lastEntry === entry) { - this.lastEntry = previousEntry; - } - entry.previousEntry = undefined; - entry.nextEntry = previousEntry; - entry.skipNext = true; - return true; - } - return false; - }; - class_1.prototype.clear = function () { - this.data = createDictionaryObject(); - this.size = 0; - var firstEntry = this.firstEntry; - var currentEntry = firstEntry.nextEntry; - while (currentEntry) { - var nextEntry = currentEntry.nextEntry; - currentEntry.previousEntry = undefined; - currentEntry.nextEntry = firstEntry; - currentEntry.skipNext = true; - currentEntry = nextEntry; - } - firstEntry.nextEntry = undefined; - this.lastEntry = firstEntry; - }; - class_1.prototype.keys = function () { - return new MapIterator(this.firstEntry, function (key) { return key; }); - }; - class_1.prototype.values = function () { - return new MapIterator(this.firstEntry, function (_key, value) { return value; }); - }; - class_1.prototype.entries = function () { - return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; }); - }; - class_1.prototype.forEach = function (action) { - var iterator = this.entries(); - while (true) { - var iterResult = iterator.next(); - if (iterResult.done) { - break; - } - var _a = iterResult.value, key = _a[0], value = _a[1]; - action(value, key); - } - }; - return class_1; - }()); - } - ts.shimMap = shimMap; function length(array) { return array ? array.length : 0; } @@ -1552,20 +1443,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; function removeMinAndVersionNumbers(fileName) { var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/; return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, ""); @@ -1942,6 +1819,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; function enableDebugInfo() { if (isDebugInfoEnabled) return; @@ -1981,6 +1885,18 @@ var ts; }); } } + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2102,8 +2018,6 @@ var ts; etwModule = undefined; } ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); var ts; (function (ts) { @@ -2406,6 +2320,7 @@ var ts; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped"; ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated"; ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); var TypeReferenceSerializationKind; @@ -2983,6 +2898,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; function enableCPUProfiler(path, cb) { @@ -3486,6 +3410,468 @@ var ts; } })(ts || (ts = {})); var ts; +(function (ts) { + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + function isAnyDirectorySeparator(charCode) { + return charCode === 47 || charCode === 92; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + function isVolumeCharacter(charCode) { + return (charCode >= 97 && charCode <= 122) || + (charCode >= 65 && charCode <= 90); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58) + return start + 1; + if (ch0 === 37 && url.charCodeAt(start + 1) === 51) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 || ch2 === 65) + return start + 3; + } + return -1; + } + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + if (ch0 === 47 || ch0 === 92) { + if (path.charCodeAt(1) !== ch0) + return 1; + var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; + return p1 + 1; + } + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 || ch2 === 92) + return 3; + if (path.length === 2) + return 2; + } + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47) { + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); + } + return ~path.length; + } + return 0; + } + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0; + if (a === undefined) + return -1; + if (b === undefined) + return 1; + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0) { + return result; + } + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); +var ts; (function (ts) { function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid) { return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid }; @@ -3509,7 +3895,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -3717,7 +4103,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -3752,6 +4138,7 @@ var ts; Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"), An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), + Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", undefined, true), @@ -3879,7 +4266,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -4052,6 +4438,8 @@ var ts; Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), + Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), + Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -4562,6 +4950,7 @@ var ts; The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), 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."), @@ -6681,7 +7070,7 @@ var ts; } ts.getDeclarationOfKind = getDeclarationOfKind; function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -6735,13 +7124,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -7447,6 +7829,11 @@ var ts; break; case 201: return getErrorSpanForArrowFunction(sourceFile, node); + case 275: + case 276: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { return getSpanOfTokenAtPosition(sourceFile, node.pos); @@ -8188,7 +8575,7 @@ var ts; (node.typeArguments[0].kind === 142 || node.typeArguments[0].kind === 139); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195) { return false; } @@ -8200,7 +8587,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -8383,7 +8770,7 @@ var ts; ts.idText(expr.expression.expression) === "Object" && ts.idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && - isBindableStaticNameExpression(expr.arguments[0]); + isBindableStaticNameExpression(expr.arguments[0], true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { @@ -8483,8 +8870,9 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + isBindableStaticAccessExpression(lhs)) { return 1; } return 5; @@ -9706,7 +10094,7 @@ var ts; ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration; function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, false); var extensionless = ts.removeFileExtension(relativePath); @@ -10156,6 +10544,23 @@ var ts; return node.kind === 75 || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75: + return node; + case 152: + do { + node = node.left; + } while (node.kind !== 75); + return node; + case 193: + do { + node = node.expression; + } while (node.kind !== 75); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 || node.kind === 103 || node.kind === 193 && isDottedName(node.expression) || @@ -10584,20 +10989,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); } @@ -10623,7 +11014,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -11485,11 +11876,17 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32) && + (kind === 193 + || kind === 194 + || kind === 195); } ts.isOptionalChain = isOptionalChain; + function isExpressionOfOptionalChainRoot(node) { + return ts.isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; function isNewExpression(node) { return node.kind === 196; } @@ -12722,7 +13119,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -12995,195 +13397,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 && charCode <= 122) || - (charCode >= 65 && charCode <= 90); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58) - return start + 1; - if (ch0 === 37 && url.charCodeAt(start + 1) === 51) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 || ch2 === 65) - return start + 3; - } - return -1; - } - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - if (ch0 === 47 || ch0 === 92) { - if (path.charCodeAt(1) !== ch0) - return 1; - var p1 = path.indexOf(ch0 === 47 ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; - return p1 + 1; - } - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 || ch2 === 92) - return 3; - if (path.length === 2) - return 2; - } - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47) { - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); - } - return ~path.length; - } - return 0; - } - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -13200,214 +13413,23 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) { return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@"); } })(ts || (ts = {})); (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 || ch === 92; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0; - if (a === undefined) - return -1; - if (b === undefined) - return 1; - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0) { - return result; - } - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 || charCode === 92; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -13423,10 +13445,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42, 63]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -13481,7 +13499,7 @@ var ts; if (usage !== "exclude" && lastComponent === "**") { return undefined; } - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -13533,7 +13551,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -13559,7 +13577,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -13569,8 +13587,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -13597,8 +13615,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -13613,12 +13631,12 @@ var ts; var includeBasePaths = []; for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) { var include = includes_1[_i]; - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); includeBasePaths.push(getIncludeBasePath(absolute)); } includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -13632,9 +13650,9 @@ var ts; function getIncludeBasePath(absolute) { var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -13769,14 +13787,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); var indexOfStar = pattern.indexOf("*"); @@ -13811,34 +13824,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -15114,7 +15099,12 @@ var ts; return finishNode(node); } var reportAtCurrentPosition = token() === 1; - return createMissingNode(75, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var isReservedWord = scanner.isReservedWord(); + var msgArg = scanner.getTokenText(); + var defaultMessage = isReservedWord ? + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : + ts.Diagnostics.Identifier_expected; + return createMissingNode(75, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -20272,6 +20262,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, { name: "target", shortName: "t", @@ -21228,92 +21227,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - marginLength = 0; - var usageColumn = []; - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - marginLength = Math.max(usageText_1.length, marginLength); - } - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache) { var configFileText; try { @@ -21583,7 +21497,7 @@ var ts; } function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -21604,12 +21518,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -21767,6 +21681,34 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) { return parseJsonConfigFileContentWorker(json, undefined, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache); } @@ -22179,7 +22121,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -23596,7 +23538,11 @@ var ts; } return 1; } - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } + var flowNodeCreated = initFlowNode; var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -23648,6 +23594,8 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -23908,7 +23856,7 @@ var ts; var isIIFE = containerFlags & 16 && !ts.hasModifier(node, 256) && !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node); if (!isIIFE) { - currentFlow = { flags: 2 }; + currentFlow = initFlowNode({ flags: 2 }); if (containerFlags & (16 | 128)) { currentFlow.node = node; } @@ -23918,7 +23866,7 @@ var ts; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; + flowNodeCreated = initFlowNode; bindChildren(node); node.flags &= ~2816; if (!(currentFlow.flags & 1) && containerFlags & 8 && ts.nodeIsPresent(node.body)) { @@ -24086,9 +24034,6 @@ var ts; case 309: bindJSDocTypeAlias(node); break; - case 307: - bindJSDocClassTag(node); - break; case 288: { bindEachFunctionsFirst(node.statements); bind(node.endOfFileToken); @@ -24127,9 +24072,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 || expr.kind === 103 || expr.kind === 101 || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -24186,10 +24130,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4, antecedents: undefined }; + return initFlowNode({ flags: 4, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8, antecedents: undefined }; + return initFlowNode({ flags: 8, antecedents: undefined }); } function setFlowNodeReferenced(flow) { flow.flags |= flow.flags & 1024 ? 2048 : 1024; @@ -24209,7 +24153,7 @@ var ts; } if (expression.kind === 105 && flags & 64 || expression.kind === 90 && flags & 32) { - if (!ts.isOptionalChainRoot(expression.parent)) { + if (!ts.isExpressionOfOptionalChainRoot(expression)) { return unreachableFlow; } } @@ -24429,7 +24373,7 @@ var ts; var tryPriors = []; var oldFlowNodeCreated = flowNodeCreated; if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; + flowNodeCreated = function (node) { return (tryPriors.push(node), initFlowNode(node)); }; } bind(node.tryBlock); flowNodeCreated = oldFlowNodeCreated; @@ -24464,7 +24408,7 @@ var ts; preFinallyPrior = finishFlowLabel(preFinallyFlow_1); } } - var preFinallyFlow = { flags: 4096, antecedent: preFinallyPrior, lock: {} }; + var preFinallyFlow = initFlowNode({ flags: 4096, antecedent: preFinallyPrior, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); @@ -24522,7 +24466,7 @@ var ts; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912; @@ -25038,7 +24982,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 }; + currentFlow = initFlowNode({ flags: 2 }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -25394,6 +25338,8 @@ var ts; case 302: case 185: return bindAnonymousTypeWorker(node); + case 307: + return bindJSDocClassTag(node); case 192: return bindObjectLiteralExpression(node); case 200: @@ -25591,7 +25537,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 : 4 | 1048576 | 512; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864, 0); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864, 0); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -25673,6 +25620,9 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, true); } function bindPrototypePropertyAssignment(lhs, parent) { @@ -25730,7 +25680,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32); } return namespaceSymbol; @@ -26996,7 +26946,6 @@ var ts; var argumentsSymbol = createSymbol(4, "arguments"); var requireSymbol = createSymbol(4, "require"); var apparentArgumentCount; - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; var checker = { getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); }, getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); }, @@ -27110,9 +27059,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -27161,7 +27110,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -27336,10 +27285,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, undefined, 0, false, false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, false, false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, false, false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, 0); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, undefined, 0, 0); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, undefined, 0, 0); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, undefined, 0, 0); var enumNumberIndexInfo = createIndexInfo(stringType, true); var iterationTypesCache = ts.createMap(); var noIterationTypes = { @@ -27483,7 +27432,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -27493,7 +27442,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -28484,7 +28433,12 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } } } else if (hasSyntheticDefault) { @@ -28566,7 +28520,12 @@ var ts; } } else { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + if (moduleSymbol.exports && moduleSymbol.exports.has("default")) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } } return symbol; @@ -28718,7 +28677,7 @@ var ts; var namespaceMeaning = 1920 | (ts.isInJSFile(name) ? meaning & 111551 : 0); var symbol; if (name.kind === 75) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, true); if (!symbol) { @@ -29551,7 +29510,7 @@ var ts; else { meaning = 788968; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, undefined, undefined, false); return (symbol && hasVisibleDeclarations(symbol, true)) || { accessibility: 1, @@ -30373,7 +30332,7 @@ var ts; function trackComputedName(accessExpression, enclosingDeclaration, context) { if (!context.tracker.trackSymbol) return; - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 | 1048576, undefined, undefined, true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551); @@ -31042,7 +31001,7 @@ var ts; var mergedMembers = locationMap.get("merged") || ts.emptyArray; if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & 16)); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); @@ -31182,7 +31141,7 @@ var ts; addResult(ts.createNamespaceExportDeclaration(ts.idText(node.name)), 0); break; case 254: - addResult(ts.createImportDeclaration(undefined, undefined, ts.createImportClause(ts.createIdentifier(localName), undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0); + addResult(ts.createImportDeclaration(undefined, undefined, ts.createImportClause(ts.createIdentifier(localName), undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0); break; case 255: addResult(ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamespaceImport(ts.createIdentifier(localName))), ts.createLiteral(getSpecifierForModuleSymbol(target, context))), 0); @@ -31190,7 +31149,7 @@ var ts; case 257: addResult(ts.createImportDeclaration(undefined, undefined, ts.createImportClause(undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0); break; case 261: var specifier = node.parent.parent.moduleSpecifier; @@ -31386,7 +31345,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863, true, true); if (sym) { includePrivateSymbol(sym); @@ -31775,7 +31734,7 @@ var ts; } if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 | 788968 | 1920, undefined, undefined, false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -32428,7 +32387,7 @@ var ts; return type_1; } if (!pushTypeResolution(symbol, 0)) { - if (symbol.flags & 512) { + if (symbol.flags & 512 && !(symbol.flags & 67108864)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -32492,7 +32451,7 @@ var ts; return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol)); } if (!popTypeResolution()) { - if (symbol.flags & 512) { + if (symbol.flags & 512 && !(symbol.flags & 67108864)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -32571,7 +32530,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -32789,6 +32750,7 @@ var ts; } function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) { @@ -32813,7 +32775,7 @@ var ts; var signatures = getSignaturesOfType(type, 1); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -33502,8 +33464,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -33511,14 +33473,12 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { - var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, undefined, undefined, sig.minArgumentCount, sig.flags & 3); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -33530,13 +33490,17 @@ var ts; result.mapper = undefined; return result; } + function getOptionalCallSignature(signature) { + return signatureIsOptionalCall(signature) ? signature : + (signature.optionalCallSignatureCache || (signature.optionalCallSignatureCache = createOptionalCallSignature(signature))); + } function createOptionalCallSignature(signature) { var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= 4; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -33561,7 +33525,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, false, false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, undefined, 0, 0)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -33708,9 +33672,7 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; - var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, undefined, undefined, minArgCount, hasRestParam, hasLiteralTypes); + var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, undefined, undefined, minArgCount, (left.flags | right.flags) & 3); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -33865,7 +33827,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor")) : ts.emptyArray; if (symbol.flags & 16) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, undefined, sig.minArgumentCount, sig.flags & 3) : undefined; })); } if (!constructSignatures.length) { @@ -34688,7 +34650,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -34715,7 +34677,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186) { - hasLiteralTypes = true; + flags |= 2; } var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || param.initializer || param.questionToken || param.dotDotDotToken || @@ -34739,8 +34701,10 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); - links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1; + } + links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, undefined, undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -34873,8 +34837,8 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, true); + if (signatureIsOptionalCall(signature)) { + type = addOptionalTypeMarker(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -34930,7 +34894,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1); @@ -35260,7 +35224,7 @@ var ts; errorType; } if (symbol.flags & 111551 && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -35271,14 +35235,21 @@ var ts; } return errorType; } - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = ts.isVariableDeclaration(decl) + && decl.initializer + && ts.isCallExpression(decl.initializer) + && ts.isRequireCall(decl.initializer, true) + && valueType.symbol; + if (isRequireAlias) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 || substitute === typeVariable) { @@ -36664,7 +36635,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -37047,7 +37018,7 @@ var ts; tp.mapper = mapper; } } - var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), undefined, undefined, signature.minArgumentCount, signature.flags & 3); result.target = signature; result.mapper = mapper; return result; @@ -37832,7 +37803,7 @@ var ts; } function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } function compareSignaturesRelated(source, target, callbackCheck, ignoreReturnTypes, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes) { @@ -40146,33 +40117,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } function propagateOptionalTypeMarker(type, wasOptional) { return wasOptional ? addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } function isCoercibleUnderDoubleEquals(source, target) { return ((source.flags & (8 | 4 | 512)) !== 0) @@ -40720,10 +40677,7 @@ var ts; } target = getUnionType(targets); if (sources.length === 0) { - var savePriority = priority; - priority |= 1; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1); return; } source = getUnionType(sources); @@ -40803,10 +40757,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4) && target.flags & 4194304) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32); contravariant = !contravariant; } else if (source.flags & 8388608 && target.flags & 8388608) { @@ -40847,6 +40798,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -40912,6 +40869,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576) { @@ -40937,6 +40906,13 @@ var ts; } } } + if (typeVariableCount === 0) { + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1); + } + return; + } if (typeVariableCount === 1 && !inferenceCircularity) { var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; }); if (unmatched.length) { @@ -40957,15 +40933,12 @@ var ts; } } if (targetFlags & 2097152 ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -40982,20 +40955,15 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; - priority |= ts.getObjectFlags(source) & 1048576 ? - 4 : 2; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 1048576 ? + 4 : + 2); } } return true; } if (constraintType.flags & 262144) { - var savePriority = priority; - priority |= 8; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8); var extendedConstraint = getConstraintOfType(constraintType); if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) { return true; @@ -41330,6 +41298,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } function containsMatchingReferenceDiscriminant(source, target) { var name; return ts.isAccessExpression(target) && @@ -41439,8 +41416,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -41791,8 +41768,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072)) { if (!(ts.getObjectFlags(t) & 256)) { return false; @@ -41860,9 +41837,18 @@ var ts; var links = getNodeLinks(node); var signature = links.effectsSignature; if (signature === undefined) { - var funcType = node.parent.kind === 225 ? getTypeOfDottedName(node.expression, undefined) : - node.expression.kind !== 101 ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225) { + funcType = getTypeOfDottedName(node.expression, undefined); + } + else if (node.expression.kind !== 101) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -41875,6 +41861,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 || predicate.kind === 3) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -41890,6 +41883,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 && flow.lock.locked) && isReachableFlowNodeWorker(flow, false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 || node.kind === 208 && (node.operatorToken.kind === 55 && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -41909,8 +41907,17 @@ var ts; } else if (flags & 512) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072) { + return false; + } } flow = flow.antecedent; } @@ -42110,6 +42117,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90) { + return unreachableNeverType; + } if (node.kind === 208) { if (node.operatorToken.kind === 55) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -42128,7 +42138,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, true) : - predicate.kind === 3 ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -42191,17 +42201,27 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 | 131072)); }); + } + else if (expr.kind === 203 && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 || t.flags & 128 && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } + else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { + return unreachableNeverType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -42305,6 +42325,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 : 8388608); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 : 8388608); }); } @@ -42353,6 +42376,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -42376,6 +42407,12 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + var effectiveTrue = operator === 34 || operator === 36 ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 || operator === 35; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 : 65536)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1) { return type; @@ -42422,16 +42459,19 @@ var ts; return type; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { + if (operator === 35 || operator === 37) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152); + } if (containsMatchingReference(reference, target)) { return declaredType; } return type; } - if (operator === 35 || operator === 37) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 && literal.text === "function") { return type; } @@ -42461,6 +42501,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { var switchTypes = getSwitchClauseTypes(switchStatement); if (!switchTypes.length) { @@ -42554,6 +42598,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152); + } if (containsMatchingReference(reference, left) && !isSyntheticThisPropertyAccess(reference)) { return declaredType; } @@ -42608,36 +42655,25 @@ var ts; return type; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 || predicate.kind === 3) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536)) { + return getTypeWithFacts(type, 2097152); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } function narrowType(type, expr, assumeTrue) { - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -43487,16 +43523,20 @@ var ts; } return undefined; } - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -43795,7 +43835,7 @@ var ts; return stringType; } case 196: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198: case 216: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -43986,8 +44026,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -44787,8 +44827,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304); @@ -44796,22 +44836,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 ? flags & 65536 ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 ? flags & 65536 ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304; if (kind) { - error(node, kind & 32768 ? kind & 65536 ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 | 131072) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384) { @@ -44820,10 +44872,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199) { @@ -44831,8 +44889,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -44885,7 +44942,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { var assignmentKind = ts.getAssignmentTargetKind(node); @@ -45163,7 +45220,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -45179,7 +45244,7 @@ var ts; 2 | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 : 0) : 0; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -45261,7 +45326,7 @@ var ts; lastParent = parent; } lastSymbol = symbol; - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; cutoffIndex++; @@ -45269,7 +45334,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, isOptionalCall ? getOptionalCallSignature(signature) : signature); } } function isSpreadArgument(arg) { @@ -45511,7 +45576,19 @@ var ts; var thisType = getThisTypeOfSignature(signature); if (thisType && thisType !== voidType && node.kind !== 196) { var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -45711,7 +45788,7 @@ var ts; if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); } } if (min < argCount && argCount < max) { @@ -45970,29 +46047,30 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1; } - return createSignature(candidates[0].declaration, undefined, thisParameter, parameters, getIntersectionType(candidates.map(getReturnTypeOfSignature)), undefined, minArgumentCount, hasRestParameter, candidates.some(function (c) { return c.hasLiteralTypes; })); + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2; + } + return createSignature(candidates[0].declaration, undefined, thisParameter, parameters, getIntersectionType(candidates.map(getReturnTypeOfSignature)), undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2)); @@ -46064,7 +46142,17 @@ var ts; } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var isOptional; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + isOptional = nonOptionalType !== funcType; + funcType = nonOptionalType; + } + else { + isOptional = false; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -46230,8 +46318,8 @@ var ts; if (apparentType.flags & 1048576) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -46372,7 +46460,7 @@ var ts; var declaration = ts.createFunctionTypeNode(undefined, [ts.createParameter(undefined, undefined, undefined, "props", undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.createTypeReferenceNode(returnNode, undefined) : ts.createKeywordTypeNode(124)); var parameterSymbol = createSymbol(1, "props"); parameterSymbol.type = result; - return createSignature(declaration, undefined, undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, undefined, 1, false, false); + return createSignature(declaration, undefined, undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, undefined, 1, 0); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -46399,7 +46487,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -46740,7 +46828,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -46757,11 +46845,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[paramCount]); var index = pos - paramCount; if (!isTupleType(restType) || restType.target.hasRestElement || index < getTypeArguments(restType).length) { @@ -46793,7 +46881,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -46802,7 +46890,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -46814,14 +46902,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -46838,7 +46926,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -46867,7 +46955,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -46875,7 +46963,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { var contextualParameterType = getRestTypeAtPosition(context, len); @@ -47209,7 +47297,7 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, false, false); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, undefined, 0, 0); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); returnOnlyType.objectFlags |= 1048576; return links.contextFreeType = returnOnlyType; @@ -47504,8 +47592,8 @@ var ts; } if (type.flags & 3145728) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -48389,7 +48477,18 @@ var ts; function getTypeOfExpression(node, cache) { var expr = ts.skipParentheses(node); if (ts.isCallExpression(expr) && expr.expression.kind !== 101 && !ts.isRequireCall(expr, true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; + var isOptional = void 0; + var funcType = void 0; + if (ts.isCallChain(expr)) { + funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + isOptional = funcType !== nonOptionalType; + funcType = checkNonNullType(nonOptionalType, expr.expression); + } + else { + isOptional = false; + funcType = checkNonNullExpression(expr.expression); + } var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); @@ -48619,7 +48718,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -49578,7 +49677,7 @@ var ts; if (!checkTypeAssignableTo(promiseConstructorType, globalPromiseConstructorLikeType, returnTypeNode, ts.Diagnostics.Type_0_is_not_a_valid_async_function_return_type_in_ES5_SlashES3_because_it_does_not_refer_to_a_Promise_compatible_constructor_value)) { return; } - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -49628,7 +49727,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 ? 788968 : 1920) | 2097152; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, undefined, undefined, true); if (rootSymbol @@ -49661,8 +49760,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181) { typeNode = typeNode.type; } @@ -51080,10 +51179,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -51100,6 +51196,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -51575,14 +51674,12 @@ var ts; } } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { + if (isPrototypeProperty(derived) || derived.flags & 4) { continue; } - else if (derived.flags & 98304) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304) { @@ -52048,22 +52145,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75: - return node; - case 152: - do { - node = node.left; - } while (node.kind !== 75); - return node; - case 193: - do { - node = node.expression; - } while (node.kind !== 75); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75: @@ -52176,7 +52257,7 @@ var ts; var target = resolveAlias(getSymbolOfNode(node)); if (target !== unknownSymbol) { if (target.flags & 111551) { - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 | 1920).flags & 1920)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -52236,7 +52317,7 @@ var ts; if (!node.parent.parent.moduleSpecifier) { var exportedName = node.propertyName || node.name; var symbol = resolveName(exportedName, exportedName.escapedText, 111551 | 788968 | 1920 | 2097152, undefined, undefined, true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -54310,10 +54391,10 @@ var ts; if (type.flags & 4 || type.flags & 8) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 && allTypesAssignableToKind(type, 128, true)) { + if (type.flags & 1048576 && allTypesAssignableToKind(type, 384, true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -55115,7 +55196,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -55180,6 +55261,18 @@ var ts; case 2: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; + function signatureIsOptionalCall(s) { + return !!(s.flags & 4); + } + ts.signatureIsOptionalCall = signatureIsOptionalCall; })(ts || (ts = {})); var ts; (function (ts) { @@ -56085,7 +56178,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } return node.expression !== expression || node.name !== name ? updateNode(setEmitFlags(createPropertyAccess(expression, name), ts.getEmitFlags(node)), node) @@ -56119,7 +56214,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -56153,7 +56250,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -56751,7 +56850,7 @@ var ts; var node = createSynthesizedNode(231); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -57806,8 +57905,11 @@ var ts; (texts || (texts = [])).push(prependNode); break; case "internal": - if (stripInternal) + if (stripInternal) { + if (!texts) + texts = []; break; + } case "text": (texts || (texts = [])).push(createUnparsedNode(section, node)); break; @@ -58902,7 +59004,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209, 57); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1) { return ts.createParen(condition); } return condition; @@ -62316,8 +62418,8 @@ var ts; } function serializeTypeList(types) { var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181) { typeNode = typeNode.type; } @@ -63237,7 +63339,7 @@ var ts; } function visitPropertyDeclaration(node) { ts.Debug.assert(!ts.some(node.decorators)); - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -71475,6 +71577,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -73016,7 +73119,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -75577,8 +75684,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference", data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -77623,6 +77730,7 @@ var ts; return resolutions; } ts.loadWithLocalCache = loadWithLocalCache; + ts.inferredTypesContainingFile = "__inferred type names__.ts"; function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) { if (!program || hasChangedAutomaticTypeDirectiveNames) { return false; @@ -77821,7 +77929,7 @@ var ts; var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray; if (typeReferences.length) { var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); - var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -79325,9 +79433,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); if (options.composite) { var rootPaths = ts.arrayToSet(rootNames, toPath); @@ -80208,6 +80313,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -80788,7 +80894,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -80824,33 +80930,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -81337,6 +81416,9 @@ var ts; if (!resolution.isInvalidated && isInvalidatedResolution(resolution, getResolutionWithResolvedFileName)) { resolution.isInvalidated = true; (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = ts.createMap())).set(containingFilePath, true); + if (containingFilePath.endsWith(ts.inferredTypesContainingFile)) { + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + } } }); }); @@ -81681,8 +81763,11 @@ var ts; } } var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName; @@ -81876,7 +81961,7 @@ var ts; ts.createWatchStatusReporter = createWatchStatusReporter; function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; return result; @@ -81900,7 +81985,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -81908,17 +81993,22 @@ var ts; } ts.listFiles = listFiles; function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; ts.addRange(diagnostics, program.getSyntacticDiagnostics(undefined, cancellationToken)); if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(undefined, cancellationToken)); + } } } - var emitResult = program.emit(undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -83647,30 +83737,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -83678,7 +83763,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -83965,18 +84050,17 @@ var ts; }); return count; } - var reportDiagnostic = ts.createDiagnosticReporter(ts.sys); - function updateReportDiagnostic(options) { - if (shouldBePretty(options)) { - reportDiagnostic = ts.createDiagnosticReporter(ts.sys, /*pretty*/ true); - } + function updateReportDiagnostic(sys, existing, options) { + return shouldBePretty(sys, options) ? + ts.createDiagnosticReporter(sys, /*pretty*/ true) : + existing; } - function defaultIsPretty() { - return !!ts.sys.writeOutputIsTTY && ts.sys.writeOutputIsTTY(); + function defaultIsPretty(sys) { + return !!sys.writeOutputIsTTY && sys.writeOutputIsTTY(); } - function shouldBePretty(options) { + function shouldBePretty(sys, options) { if (!options || typeof options.pretty === "undefined") { - return defaultIsPretty(); + return defaultIsPretty(sys); } return options.pretty; } @@ -83998,258 +84082,395 @@ var ts; ts.sort(ts.optionDeclarations, function (a, b) { return ts.compareStringsCaseInsensitive(a.name, b.name); }) : ts.filter(ts.optionDeclarations.slice(), function (v) { return !!v.showInSimplifiedHelpView; }); } - function executeCommandLineWorker(commandLine) { + function printVersion(sys) { + sys.write(ts.getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + sys.newLine); + } + function printHelp(sys, optionsList, syntaxPrefix) { + if (syntaxPrefix === void 0) { syntaxPrefix = ""; } + var output = []; + // We want to align our "syntax" and "examples" commands to a certain margin. + var syntaxLength = ts.getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; + var examplesLength = ts.getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; + var marginLength = Math.max(syntaxLength, examplesLength); + // Build up the syntactic skeleton. + var syntax = makePadding(marginLength - syntaxLength); + syntax += "tsc " + syntaxPrefix + "[" + ts.getDiagnosticText(ts.Diagnostics.options) + "] [" + ts.getDiagnosticText(ts.Diagnostics.file) + "...]"; + output.push(ts.getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); + output.push(sys.newLine + sys.newLine); + // Build up the list of examples. + var padding = makePadding(marginLength); + output.push(ts.getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + sys.newLine); + output.push(padding + "tsc @args.txt" + sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + sys.newLine); + output.push(sys.newLine); + output.push(ts.getDiagnosticText(ts.Diagnostics.Options_Colon) + sys.newLine); + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + var usageColumn = []; // Things like "-d, --declaration" go in here. + var descriptionColumn = []; + var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind + for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { + var option = optionsList_1[_i]; + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + var usageText_1 = " "; + if (option.shortName) { + usageText_1 += "-" + option.shortName; + usageText_1 += getParamType(option); + usageText_1 += ", "; + } + usageText_1 += "--" + option.name; + usageText_1 += getParamType(option); + usageColumn.push(usageText_1); + var description = void 0; + if (option.name === "lib") { + description = ts.getDiagnosticText(option.description); + var element = option.element; + var typeMap = element.type; + optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); + } + else { + description = ts.getDiagnosticText(option.description); + } + descriptionColumn.push(description); + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText_1.length, marginLength); + } + // Special case that can't fit in the loop. + var usageText = " @<" + ts.getDiagnosticText(ts.Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(ts.getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + // Print out each row, aligning all the descriptions on the same column. + for (var i = 0; i < usageColumn.length; i++) { + var usage = usageColumn[i]; + var description = descriptionColumn[i]; + var kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine); + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { + var kind = kindsList_1[_a]; + output.push(kind + " "); + } + output.push(sys.newLine); + } + } + for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { + var line = output_1[_b]; + sys.write(line); + } + return; + function getParamType(option) { + if (option.paramType !== undefined) { + return " " + ts.getDiagnosticText(option.paramType); + } + return ""; + } + function makePadding(paddingLength) { + return Array(paddingLength + 1).join(" "); + } + } + function executeCommandLineWorker(sys, cb, commandLine) { + var reportDiagnostic = ts.createDiagnosticReporter(sys); if (commandLine.options.build) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_build_must_be_the_first_command_line_argument)); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } // Configuration file name (if any) var configFileName; if (commandLine.options.locale) { - ts.validateLocaleAndSetLanguage(commandLine.options.locale, ts.sys, commandLine.errors); + ts.validateLocaleAndSetLanguage(commandLine.options.locale, sys, commandLine.errors); } // If there are any errors due to command line parsing and/or // setting up localization, report them and quit. if (commandLine.errors.length > 0) { commandLine.errors.forEach(reportDiagnostic); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (commandLine.options.init) { - writeConfigFile(commandLine.options, commandLine.fileNames); - return ts.sys.exit(ts.ExitStatus.Success); + writeConfigFile(sys, reportDiagnostic, commandLine.options, commandLine.fileNames); + return sys.exit(ts.ExitStatus.Success); } if (commandLine.options.version) { - ts.printVersion(); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + return sys.exit(ts.ExitStatus.Success); } if (commandLine.options.help || commandLine.options.all) { - ts.printVersion(); - ts.printHelp(getOptionsForHelp(commandLine)); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + printHelp(sys, getOptionsForHelp(commandLine)); + return sys.exit(ts.ExitStatus.Success); + } + if (commandLine.options.watch && commandLine.options.listFilesOnly) { + reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "listFilesOnly")); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (commandLine.options.project) { if (commandLine.fileNames.length !== 0) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line)); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } var fileOrDirectory = ts.normalizePath(commandLine.options.project); - if (!fileOrDirectory /* current directory "." */ || ts.sys.directoryExists(fileOrDirectory)) { + if (!fileOrDirectory /* current directory "." */ || sys.directoryExists(fileOrDirectory)) { configFileName = ts.combinePaths(fileOrDirectory, "tsconfig.json"); - if (!ts.sys.fileExists(configFileName)) { + if (!sys.fileExists(configFileName)) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project)); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } else { configFileName = fileOrDirectory; - if (!ts.sys.fileExists(configFileName)) { + if (!sys.fileExists(configFileName)) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project)); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } } } else if (commandLine.fileNames.length === 0) { - var searchPath = ts.normalizePath(ts.sys.getCurrentDirectory()); - configFileName = ts.findConfigFile(searchPath, ts.sys.fileExists); + var searchPath = ts.normalizePath(sys.getCurrentDirectory()); + configFileName = ts.findConfigFile(searchPath, sys.fileExists); } if (commandLine.fileNames.length === 0 && !configFileName) { - ts.printVersion(); - ts.printHelp(getOptionsForHelp(commandLine)); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + printHelp(sys, getOptionsForHelp(commandLine)); + return sys.exit(ts.ExitStatus.Success); } - var commandLineOptions = commandLine.options; + var currentDirectory = sys.getCurrentDirectory(); + var commandLineOptions = ts.convertToOptionsWithAbsolutePaths(commandLine.options, function (fileName) { return ts.getNormalizedAbsolutePath(fileName, currentDirectory); }); if (configFileName) { - var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, ts.sys, reportDiagnostic); // TODO: GH#18217 + var configParseResult = ts.parseConfigFileWithSystem(configFileName, commandLineOptions, sys, reportDiagnostic); // TODO: GH#18217 if (commandLineOptions.showConfig) { if (configParseResult.errors.length !== 0) { - updateReportDiagnostic(configParseResult.options); + reportDiagnostic = updateReportDiagnostic(sys, reportDiagnostic, configParseResult.options); configParseResult.errors.forEach(reportDiagnostic); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } // eslint-disable-next-line no-null/no-null - ts.sys.write(JSON.stringify(ts.convertToTSConfig(configParseResult, configFileName, ts.sys), null, 4) + ts.sys.newLine); - return ts.sys.exit(ts.ExitStatus.Success); + sys.write(JSON.stringify(ts.convertToTSConfig(configParseResult, configFileName, sys), null, 4) + sys.newLine); + return sys.exit(ts.ExitStatus.Success); } - updateReportDiagnostic(configParseResult.options); + reportDiagnostic = updateReportDiagnostic(sys, reportDiagnostic, configParseResult.options); if (ts.isWatchSet(configParseResult.options)) { - reportWatchModeWithoutSysSupport(); - createWatchOfConfigFile(configParseResult, commandLineOptions); + if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) + return; + createWatchOfConfigFile(sys, reportDiagnostic, configParseResult, commandLineOptions); } else if (ts.isIncrementalCompilation(configParseResult.options)) { - performIncrementalCompilation(configParseResult); + performIncrementalCompilation(sys, reportDiagnostic, cb, configParseResult); } else { - performCompilation(configParseResult.fileNames, configParseResult.projectReferences, configParseResult.options, ts.getConfigFileParsingDiagnostics(configParseResult)); + performCompilation(sys, reportDiagnostic, cb, configParseResult); } } else { if (commandLineOptions.showConfig) { // eslint-disable-next-line no-null/no-null - ts.sys.write(JSON.stringify(ts.convertToTSConfig(commandLine, ts.combinePaths(ts.sys.getCurrentDirectory(), "tsconfig.json"), ts.sys), null, 4) + ts.sys.newLine); - return ts.sys.exit(ts.ExitStatus.Success); + sys.write(JSON.stringify(ts.convertToTSConfig(commandLine, ts.combinePaths(currentDirectory, "tsconfig.json"), sys), null, 4) + sys.newLine); + return sys.exit(ts.ExitStatus.Success); } - updateReportDiagnostic(commandLineOptions); + reportDiagnostic = updateReportDiagnostic(sys, reportDiagnostic, commandLineOptions); if (ts.isWatchSet(commandLineOptions)) { - reportWatchModeWithoutSysSupport(); - createWatchOfFilesAndCompilerOptions(commandLine.fileNames, commandLineOptions); + if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) + return; + createWatchOfFilesAndCompilerOptions(sys, reportDiagnostic, commandLine.fileNames, commandLineOptions); } else if (ts.isIncrementalCompilation(commandLineOptions)) { - performIncrementalCompilation(commandLine); + performIncrementalCompilation(sys, reportDiagnostic, cb, __assign(__assign({}, commandLine), { options: commandLineOptions })); } else { - performCompilation(commandLine.fileNames, /*references*/ undefined, commandLineOptions); + performCompilation(sys, reportDiagnostic, cb, __assign(__assign({}, commandLine), { options: commandLineOptions })); } } } - function executeCommandLine(args) { - if (args.length > 0 && args[0].charCodeAt(0) === 45 /* minus */) { - var firstOption = args[0].slice(args[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); - if (firstOption === "build" || firstOption === "b") { - return performBuild(args.slice(1)); - } + function isBuild(commandLineArgs) { + if (commandLineArgs.length > 0 && commandLineArgs[0].charCodeAt(0) === 45 /* minus */) { + var firstOption = commandLineArgs[0].slice(commandLineArgs[0].charCodeAt(1) === 45 /* minus */ ? 2 : 1).toLowerCase(); + return firstOption === "build" || firstOption === "b"; } - var commandLine = ts.parseCommandLine(args); - if (commandLine.options.generateCpuProfile && ts.sys.enableCPUProfiler) { - ts.sys.enableCPUProfiler(commandLine.options.generateCpuProfile, function () { return executeCommandLineWorker(commandLine); }); + return false; + } + ts.isBuild = isBuild; + function executeCommandLine(system, cb, commandLineArgs) { + if (isBuild(commandLineArgs)) { + return performBuild(system, cb, commandLineArgs.slice(1)); + } + var commandLine = ts.parseCommandLine(commandLineArgs, function (path) { return system.readFile(path); }); + if (commandLine.options.generateCpuProfile && system.enableCPUProfiler) { + system.enableCPUProfiler(commandLine.options.generateCpuProfile, function () { return executeCommandLineWorker(system, cb, commandLine); }); } else { - executeCommandLineWorker(commandLine); + executeCommandLineWorker(system, cb, commandLine); } } ts.executeCommandLine = executeCommandLine; - function reportWatchModeWithoutSysSupport() { - if (!ts.sys.watchFile || !ts.sys.watchDirectory) { + function reportWatchModeWithoutSysSupport(sys, reportDiagnostic) { + if (!sys.watchFile || !sys.watchDirectory) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); - ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return true; } + return false; } - function performBuildWorker(buildOptions, projects, errors) { + function performBuildWorker(sys, cb, buildOptions, projects, errors) { // Update to pretty if host supports it - updateReportDiagnostic(buildOptions); + var reportDiagnostic = updateReportDiagnostic(sys, ts.createDiagnosticReporter(sys), buildOptions); if (buildOptions.locale) { - ts.validateLocaleAndSetLanguage(buildOptions.locale, ts.sys, errors); + ts.validateLocaleAndSetLanguage(buildOptions.locale, sys, errors); } if (errors.length > 0) { errors.forEach(reportDiagnostic); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.help) { - ts.printVersion(); - ts.printHelp(ts.buildOpts, "--build "); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + printHelp(sys, ts.buildOpts, "--build "); + return sys.exit(ts.ExitStatus.Success); } if (projects.length === 0) { - ts.printVersion(); - ts.printHelp(ts.buildOpts, "--build "); - return ts.sys.exit(ts.ExitStatus.Success); + printVersion(sys); + printHelp(sys, ts.buildOpts, "--build "); + return sys.exit(ts.ExitStatus.Success); } - if (!ts.sys.getModifiedTime || !ts.sys.setModifiedTime || (buildOptions.clean && !ts.sys.deleteFile)) { + if (!sys.getModifiedTime || !sys.setModifiedTime || (buildOptions.clean && !sys.deleteFile)) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); - return ts.sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); + return sys.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped); } if (buildOptions.watch) { - reportWatchModeWithoutSysSupport(); - var buildHost_1 = ts.createSolutionBuilderWithWatchHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty(buildOptions)), createWatchStatusReporter(buildOptions)); - updateCreateProgram(buildHost_1); - buildHost_1.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(program.getProgram()); }; + if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) + return; + var buildHost_1 = ts.createSolutionBuilderWithWatchHost(sys, + /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(sys, shouldBePretty(sys, buildOptions)), createWatchStatusReporter(sys, buildOptions)); + if (cb && cb.onSolutionBuilderHostCreate) + cb.onSolutionBuilderHostCreate(buildHost_1); + updateCreateProgram(sys, buildHost_1); + buildHost_1.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(sys, program.getProgram()); }; var builder_1 = ts.createSolutionBuilderWithWatch(buildHost_1, projects, buildOptions); builder_1.build(); return; } - var buildHost = ts.createSolutionBuilderHost(ts.sys, /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(ts.sys, shouldBePretty(buildOptions)), createReportErrorSummary(buildOptions)); - updateCreateProgram(buildHost); - buildHost.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(program.getProgram()); }; + var buildHost = ts.createSolutionBuilderHost(sys, + /*createProgram*/ undefined, reportDiagnostic, ts.createBuilderStatusReporter(sys, shouldBePretty(sys, buildOptions)), createReportErrorSummary(sys, buildOptions)); + if (cb && cb.onSolutionBuilderHostCreate) + cb.onSolutionBuilderHostCreate(buildHost); + updateCreateProgram(sys, buildHost); + buildHost.afterProgramEmitAndDiagnostics = function (program) { return reportStatistics(sys, program.getProgram()); }; var builder = ts.createSolutionBuilder(buildHost, projects, buildOptions); - return ts.sys.exit(buildOptions.clean ? builder.clean() : builder.build()); + var exitStatus = buildOptions.clean ? builder.clean() : builder.build(); + if (cb && cb.onSolutionBuildComplete) + cb.onSolutionBuildComplete(builder.getAllParsedConfigs()); + return sys.exit(exitStatus); } - function performBuild(args) { + function performBuild(sys, cb, args) { var _a = ts.parseBuildCommand(args), buildOptions = _a.buildOptions, projects = _a.projects, errors = _a.errors; - if (buildOptions.generateCpuProfile && ts.sys.enableCPUProfiler) { - ts.sys.enableCPUProfiler(buildOptions.generateCpuProfile, function () { return performBuildWorker(buildOptions, projects, errors); }); + if (buildOptions.generateCpuProfile && sys.enableCPUProfiler) { + sys.enableCPUProfiler(buildOptions.generateCpuProfile, function () { return performBuildWorker(sys, cb, buildOptions, projects, errors); }); } else { - performBuildWorker(buildOptions, projects, errors); + performBuildWorker(sys, cb, buildOptions, projects, errors); } } - function createReportErrorSummary(options) { - return shouldBePretty(options) ? - function (errorCount) { return ts.sys.write(ts.getErrorSummaryText(errorCount, ts.sys.newLine)); } : + function createReportErrorSummary(sys, options) { + return shouldBePretty(sys, options) ? + function (errorCount) { return sys.write(ts.getErrorSummaryText(errorCount, sys.newLine)); } : undefined; } - function performCompilation(rootNames, projectReferences, options, configFileParsingDiagnostics) { - var host = ts.createCompilerHost(options); + function performCompilation(sys, reportDiagnostic, cb, config) { + var fileNames = config.fileNames, options = config.options, projectReferences = config.projectReferences; + var host = ts.createCompilerHostWorker(options, /*setParentPos*/ undefined, sys); + if (cb && cb.onCompilerHostCreate) + cb.onCompilerHostCreate(host); var currentDirectory = host.getCurrentDirectory(); var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames()); ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, currentDirectory, getCanonicalFileName); }); - enableStatistics(options); + enableStatistics(sys, options); var programOptions = { - rootNames: rootNames, + rootNames: fileNames, options: options, projectReferences: projectReferences, host: host, - configFileParsingDiagnostics: configFileParsingDiagnostics + configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(config) }; var program = ts.createProgram(programOptions); - var exitStatus = ts.emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, function (s) { return ts.sys.write(s + ts.sys.newLine); }, createReportErrorSummary(options)); - reportStatistics(program); - return ts.sys.exit(exitStatus); + var exitStatus = ts.emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, function (s) { return sys.write(s + sys.newLine); }, createReportErrorSummary(sys, options)); + reportStatistics(sys, program); + if (cb && cb.onCompilationComplete) + cb.onCompilationComplete(config); + return sys.exit(exitStatus); } - function performIncrementalCompilation(config) { + function performIncrementalCompilation(sys, reportDiagnostic, cb, config) { var options = config.options, fileNames = config.fileNames, projectReferences = config.projectReferences; - enableStatistics(options); - return ts.sys.exit(ts.performIncrementalCompilation({ + enableStatistics(sys, options); + var host = ts.createIncrementalCompilerHost(options, sys); + if (cb && cb.onCompilerHostCreate) + cb.onCompilerHostCreate(host); + var exitStatus = ts.performIncrementalCompilation({ + host: host, + system: sys, rootNames: fileNames, options: options, configFileParsingDiagnostics: ts.getConfigFileParsingDiagnostics(config), projectReferences: projectReferences, reportDiagnostic: reportDiagnostic, - reportErrorSummary: createReportErrorSummary(options), - afterProgramEmitAndDiagnostics: function (builderProgram) { return reportStatistics(builderProgram.getProgram()); } - })); + reportErrorSummary: createReportErrorSummary(sys, options), + afterProgramEmitAndDiagnostics: function (builderProgram) { return reportStatistics(sys, builderProgram.getProgram()); } + }); + if (cb && cb.onCompilationComplete) + cb.onCompilationComplete(config); + return sys.exit(exitStatus); } - function updateCreateProgram(host) { + function updateCreateProgram(sys, host) { var compileUsingBuilder = host.createProgram; host.createProgram = function (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) { ts.Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); if (options !== undefined) { - enableStatistics(options); + enableStatistics(sys, options); } return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); }; } - function updateWatchCompilationHost(watchCompilerHost) { - updateCreateProgram(watchCompilerHost); + function updateWatchCompilationHost(sys, watchCompilerHost) { + updateCreateProgram(sys, watchCompilerHost); var emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate; // TODO: GH#18217 watchCompilerHost.afterProgramCreate = function (builderProgram) { emitFilesUsingBuilder(builderProgram); - reportStatistics(builderProgram.getProgram()); + reportStatistics(sys, builderProgram.getProgram()); }; } - function createWatchStatusReporter(options) { - return ts.createWatchStatusReporter(ts.sys, shouldBePretty(options)); + function createWatchStatusReporter(sys, options) { + return ts.createWatchStatusReporter(sys, shouldBePretty(sys, options)); } - function createWatchOfConfigFile(configParseResult, optionsToExtend) { - var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, ts.sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); // TODO: GH#18217 - updateWatchCompilationHost(watchCompilerHost); + function createWatchOfConfigFile(sys, reportDiagnostic, configParseResult, optionsToExtend) { + var watchCompilerHost = ts.createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath, optionsToExtend, sys, + /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(sys, configParseResult.options)); // TODO: GH#18217 + updateWatchCompilationHost(sys, watchCompilerHost); watchCompilerHost.configFileParsingResult = configParseResult; ts.createWatchProgram(watchCompilerHost); } - function createWatchOfFilesAndCompilerOptions(rootFiles, options) { - var watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, ts.sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(options)); - updateWatchCompilationHost(watchCompilerHost); + function createWatchOfFilesAndCompilerOptions(sys, reportDiagnostic, rootFiles, options) { + var watchCompilerHost = ts.createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, sys, + /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(sys, options)); + updateWatchCompilationHost(sys, watchCompilerHost); ts.createWatchProgram(watchCompilerHost); } - function enableStatistics(compilerOptions) { - if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { + function canReportDiagnostics(system, compilerOptions) { + return system === ts.sys && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); + } + function enableStatistics(sys, compilerOptions) { + if (canReportDiagnostics(sys, compilerOptions)) { ts.performance.enable(); } } - function reportStatistics(program) { + function reportStatistics(sys, program) { var statistics; var compilerOptions = program.getCompilerOptions(); - if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { + if (canReportDiagnostics(sys, compilerOptions)) { statistics = []; - var memoryUsed = ts.sys.getMemoryUsage ? ts.sys.getMemoryUsage() : -1; + var memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; reportCountStatistic("Files", program.getSourceFiles().length); reportCountStatistic("Lines", countLines(program)); reportCountStatistic("Nodes", program.getNodeCount()); @@ -84300,7 +84521,7 @@ var ts; } for (var _b = 0, statistics_2 = statistics; _b < statistics_2.length; _b++) { var _c = statistics_2[_b], name = _c.name, value = _c.value; - ts.sys.write(padRight(name + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + ts.sys.newLine); + sys.write(padRight(name + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + sys.newLine); } } function reportStatisticalValue(name, value) { @@ -84313,14 +84534,14 @@ var ts; reportStatisticalValue(name, (time / 1000).toFixed(2) + "s"); } } - function writeConfigFile(options, fileNames) { - var currentDirectory = ts.sys.getCurrentDirectory(); + function writeConfigFile(sys, reportDiagnostic, options, fileNames) { + var currentDirectory = sys.getCurrentDirectory(); var file = ts.normalizePath(ts.combinePaths(currentDirectory, "tsconfig.json")); - if (ts.sys.fileExists(file)) { + if (sys.fileExists(file)) { reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file)); } else { - ts.sys.writeFile(file, ts.generateTSConfig(options, fileNames, ts.sys.newLine)); + sys.writeFile(file, ts.generateTSConfig(options, fileNames, sys.newLine)); reportDiagnostic(ts.createCompilerDiagnostic(ts.Diagnostics.Successfully_created_a_tsconfig_json_file)); } return; @@ -84335,4 +84556,10 @@ if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnviron if (ts.sys.setBlocking) { ts.sys.setBlocking(); } -ts.executeCommandLine(ts.sys.args); +// This file actually uses arguments passed on commandline and executes it +ts.executeCommandLine(ts.sys, { + onCompilerHostCreate: ts.noop, + onCompilationComplete: ts.noop, + onSolutionBuilderHostCreate: ts.noop, + onSolutionBuildComplete: ts.noop +}, ts.sys.args); diff --git a/lib/tsserver.js b/lib/tsserver.js index c7890265e9e..a586de9540d 100644 --- a/lib/tsserver.js +++ b/lib/tsserver.js @@ -107,22 +107,32 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ function createMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createMap = createMap; + /** Create a new map from an array of entries. */ function createMapFromEntries(entries) { var map = createMap(); for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { @@ -132,8 +142,9 @@ var ts; return map; } ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ function createMapFromTemplate(template) { - var map = new ts.MapCtr(); + var map = new ts.Map(); // Copies keys/values from template. Note that for..in will not throw if // template is undefined, and instead will just exit the loop. for (var key in template) { @@ -144,147 +155,6 @@ var ts; return map; } ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { - var MapIterator = /** @class */ (function () { - function MapIterator(currentEntry, selector) { - this.currentEntry = currentEntry; - this.selector = selector; - } - MapIterator.prototype.next = function () { - // Navigate to the next entry. - while (this.currentEntry) { - var skipNext = !!this.currentEntry.skipNext; - this.currentEntry = this.currentEntry.nextEntry; - if (!skipNext) { - break; - } - } - if (this.currentEntry) { - return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false }; - } - else { - return { value: undefined, done: true }; - } - }; - return MapIterator; - }()); - return /** @class */ (function () { - function class_1() { - this.data = createDictionaryObject(); - this.size = 0; - // Create a first (stub) map entry that will not contain a key - // and value but serves as starting point for iterators. - this.firstEntry = {}; - // When the map is empty, the last entry is the same as the - // first one. - this.lastEntry = this.firstEntry; - } - class_1.prototype.get = function (key) { - var entry = this.data[key]; - return entry && entry.value; - }; - class_1.prototype.set = function (key, value) { - if (!this.has(key)) { - this.size++; - // Create a new entry that will be appended at the - // end of the linked list. - var newEntry = { - key: key, - value: value - }; - this.data[key] = newEntry; - // Adjust the references. - var previousLastEntry = this.lastEntry; - previousLastEntry.nextEntry = newEntry; - newEntry.previousEntry = previousLastEntry; - this.lastEntry = newEntry; - } - else { - this.data[key].value = value; - } - return this; - }; - class_1.prototype.has = function (key) { - // eslint-disable-next-line no-in-operator - return key in this.data; - }; - class_1.prototype.delete = function (key) { - if (this.has(key)) { - this.size--; - var entry = this.data[key]; - delete this.data[key]; - // Adjust the linked list references of the neighbor entries. - var previousEntry = entry.previousEntry; - previousEntry.nextEntry = entry.nextEntry; - if (entry.nextEntry) { - entry.nextEntry.previousEntry = previousEntry; - } - // When the deleted entry was the last one, we need to - // adjust the lastEntry reference. - if (this.lastEntry === entry) { - this.lastEntry = previousEntry; - } - // Adjust the forward reference of the deleted entry - // in case an iterator still references it. This allows us - // to throw away the entry, but when an active iterator - // (which points to the current entry) continues, it will - // navigate to the entry that originally came before the - // current one and skip it. - entry.previousEntry = undefined; - entry.nextEntry = previousEntry; - entry.skipNext = true; - return true; - } - return false; - }; - class_1.prototype.clear = function () { - this.data = createDictionaryObject(); - this.size = 0; - // Reset the linked list. Note that we must adjust the forward - // references of the deleted entries to ensure iterators stuck - // in the middle of the list don't continue with deleted entries, - // but can continue with new entries added after the clear() - // operation. - var firstEntry = this.firstEntry; - var currentEntry = firstEntry.nextEntry; - while (currentEntry) { - var nextEntry = currentEntry.nextEntry; - currentEntry.previousEntry = undefined; - currentEntry.nextEntry = firstEntry; - currentEntry.skipNext = true; - currentEntry = nextEntry; - } - firstEntry.nextEntry = undefined; - this.lastEntry = firstEntry; - }; - class_1.prototype.keys = function () { - return new MapIterator(this.firstEntry, function (key) { return key; }); - }; - class_1.prototype.values = function () { - return new MapIterator(this.firstEntry, function (_key, value) { return value; }); - }; - class_1.prototype.entries = function () { - return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; }); - }; - class_1.prototype.forEach = function (action) { - var iterator = this.entries(); - while (true) { - var iterResult = iterator.next(); - if (iterResult.done) { - break; - } - var _a = iterResult.value, key = _a[0], value = _a[1]; - action(value, key); - } - }; - return class_1; - }()); - } - ts.shimMap = shimMap; function length(array) { return array ? array.length : 0; } @@ -1866,20 +1736,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2280,6 +2136,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2323,6 +2206,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2486,8 +2383,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3382,6 +3277,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3437,6 +3333,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3446,6 +3344,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3887,6 +3793,18 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsOptionalCall"] = 4] = "IsOptionalCall"; + // We do not propagate `IsOptionalCall` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -5058,6 +4976,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5196,6 +5123,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5640,6 +5568,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5667,7 +6262,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5875,7 +6470,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5910,6 +6505,7 @@ var ts; Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"), An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), + Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -6037,7 +6633,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6210,6 +6805,8 @@ var ts; Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), + Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), + Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -6720,6 +7317,7 @@ var ts; The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), 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."), @@ -9055,7 +9653,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9111,13 +9709,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9924,6 +10515,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10736,7 +11332,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10748,7 +11344,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10967,7 +11563,7 @@ var ts; ts.idText(expr.expression.expression) === "Object" && ts.idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && - isBindableStaticNameExpression(expr.arguments[0]); + isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { @@ -11075,9 +11671,11 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } // F.G...x = expr @@ -12403,7 +13001,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12925,6 +13523,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13443,20 +14058,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13483,7 +14084,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14548,11 +15149,21 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return ts.isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15914,7 +16525,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16189,273 +16805,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16472,15 +16821,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16490,229 +16839,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16731,10 +16859,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16810,7 +16934,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16872,7 +16996,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16901,7 +17025,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16911,8 +17035,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16939,8 +17063,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16962,14 +17086,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16986,9 +17110,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17153,14 +17277,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17203,36 +17322,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18743,7 +18832,12 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var isReservedWord = scanner.isReservedWord(); + var msgArg = scanner.getTokenText(); + var defaultMessage = isReservedWord ? + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : + ts.Diagnostics.Identifier_expected; + return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -25070,6 +25164,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -26062,6 +26165,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26070,104 +26174,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26486,7 +26493,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26507,12 +26514,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26689,6 +26696,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27139,7 +27175,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28923,7 +28959,11 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } + var flowNodeCreated = initFlowNode; var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28987,6 +29027,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29342,7 +29385,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29354,7 +29397,7 @@ var ts; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; + flowNodeCreated = initFlowNode; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29523,9 +29566,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29565,9 +29605,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29624,10 +29663,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29648,7 +29687,7 @@ var ts; } if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { + if (!ts.isExpressionOfOptionalChainRoot(expression)) { return unreachableFlow; } } @@ -29873,7 +29912,7 @@ var ts; // as possible antecedents of the start of the `catch` or `finally` blocks. // Don't bother intercepting the call if there's no finally or catch block that needs the information if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; + flowNodeCreated = function (node) { return (tryPriors.push(node), initFlowNode(node)); }; } bind(node.tryBlock); flowNodeCreated = oldFlowNodeCreated; @@ -29937,7 +29976,7 @@ var ts; // // extra edges that we inject allows to control this behavior // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); @@ -30004,7 +30043,7 @@ var ts; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30594,7 +30633,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -31017,6 +31056,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31236,7 +31277,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31325,6 +31367,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31399,7 +31445,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32900,12 +32946,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33044,9 +33084,6 @@ var ts; var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33165,9 +33202,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33216,7 +33253,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33401,10 +33438,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33557,7 +33594,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33567,7 +33604,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -34755,7 +34792,12 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } } } else if (hasSyntheticDefault) { @@ -34859,7 +34901,12 @@ var ts; } } else { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + if (moduleSymbol.exports && moduleSymbol.exports.has("default" /* Default */)) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } } return symbol; @@ -35035,7 +35082,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35998,7 +36045,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36853,7 +36900,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37622,7 +37669,7 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & 16 /* Function */)); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); @@ -37833,7 +37880,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37845,7 +37896,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -38114,7 +38165,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38537,7 +38588,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -39297,7 +39348,7 @@ var ts; // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39365,7 +39416,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39448,7 +39499,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39684,6 +39737,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39714,7 +39768,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40551,8 +40605,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40560,15 +40614,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40580,13 +40632,17 @@ var ts; result.mapper = undefined; return result; } + function getOptionalCallSignature(signature) { + return signatureIsOptionalCall(signature) ? signature : + (signature.optionalCallSignatureCache || (signature.optionalCallSignatureCache = createOptionalCallSignature(signature))); + } function createOptionalCallSignature(signature) { var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= 4 /* IsOptionalCall */; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40611,7 +40667,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40775,11 +40831,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40952,7 +41006,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41892,7 +41946,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41923,7 +41977,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41949,9 +42003,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42094,8 +42150,8 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signatureIsOptionalCall(signature)) { + type = addOptionalTypeMarker(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42151,7 +42207,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42525,7 +42581,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42538,18 +42594,25 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function fakes special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = ts.isVariableDeclaration(decl) + && decl.initializer + && ts.isCallExpression(decl.initializer) + && ts.isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ true) + && valueType.symbol; + if (isRequireAlias) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -44090,7 +44153,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44505,7 +44568,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45393,7 +45456,7 @@ var ts; */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** @@ -48078,37 +48141,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } function propagateOptionalTypeMarker(type, wasOptional) { return wasOptional ? addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48743,10 +48788,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48846,10 +48888,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48901,6 +48940,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48966,6 +49011,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -48995,6 +49052,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49026,15 +49093,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49055,14 +49119,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49070,10 +49132,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -49451,6 +49510,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49571,8 +49639,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49941,8 +50009,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50023,9 +50091,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50038,6 +50115,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50053,6 +50137,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50072,8 +50161,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50307,6 +50405,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50325,7 +50426,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50396,17 +50497,27 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } + else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { + return unreachableNeverType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50548,6 +50659,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50596,6 +50710,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50619,6 +50741,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50666,8 +50797,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50675,9 +50812,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50710,6 +50844,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50842,6 +50980,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50914,39 +51055,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -52007,18 +52137,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52377,7 +52511,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52592,8 +52726,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -53590,8 +53724,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53599,22 +53733,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53623,10 +53769,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53634,8 +53786,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53688,7 +53839,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -54010,7 +54161,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54026,7 +54185,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54127,7 +54286,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54138,7 +54297,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, isOptionalCall ? getOptionalCallSignature(signature) : signature); } } function isSpreadArgument(arg) { @@ -54433,7 +54592,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54660,7 +54831,7 @@ var ts; if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); } } if (min < argCount && argCount < max) { @@ -54986,34 +55157,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55094,7 +55265,17 @@ var ts; } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var isOptional; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + isOptional = nonOptionalType !== funcType; + funcType = nonOptionalType; + } + else { + isOptional = false; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55316,8 +55497,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55476,9 +55657,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55511,7 +55690,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55892,7 +56071,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55909,11 +56088,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55948,7 +56127,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55957,7 +56136,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55969,14 +56148,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -55993,7 +56172,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56026,7 +56205,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56034,7 +56213,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56439,7 +56618,7 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); returnOnlyType.objectFlags |= 1048576 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; @@ -56772,8 +56951,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57772,7 +57951,18 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; + var isOptional = void 0; + var funcType = void 0; + if (ts.isCallChain(expr)) { + funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + isOptional = funcType !== nonOptionalType; + funcType = checkNonNullType(nonOptionalType, expr.expression); + } + else { + isOptional = false; + funcType = checkNonNullExpression(expr.expression); + } var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); @@ -58029,7 +58219,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59204,7 +59394,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59261,7 +59451,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59301,8 +59491,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61077,10 +61267,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61101,6 +61288,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61652,15 +61842,13 @@ var ts; } } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62166,22 +62354,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62311,7 +62483,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62378,7 +62550,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64684,10 +64856,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65570,7 +65742,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65640,6 +65812,18 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; + function signatureIsOptionalCall(s) { + return !!(s.flags & 4 /* IsOptionalCall */); + } + ts.signatureIsOptionalCall = signatureIsOptionalCall; })(ts || (ts = {})); var ts; (function (ts) { @@ -66573,7 +66757,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66611,7 +66797,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66645,7 +66833,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67247,7 +67437,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -68347,8 +68537,11 @@ var ts; (texts || (texts = [])).push(prependNode); break; case "internal" /* Internal */: - if (stripInternal) + if (stripInternal) { + if (!texts) + texts = []; break; + } // falls through case "text" /* Text */: (texts || (texts = [])).push(createUnparsedNode(section, node)); @@ -69770,7 +69963,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -74213,8 +74406,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -75645,7 +75838,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -87660,6 +87853,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89431,7 +89625,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92185,8 +92383,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94456,6 +94654,8 @@ var ts; return resolutions; } ts.loadWithLocalCache = loadWithLocalCache; + /* @internal */ + ts.inferredTypesContainingFile = "__inferred type names__.ts"; /** * Determines if program structure is upto date or needs to be recreated */ @@ -94708,7 +94908,7 @@ var ts; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); - var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -96446,9 +96646,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97493,6 +97690,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98223,7 +98421,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98259,33 +98457,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -98829,6 +99000,10 @@ var ts; // 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); + // When its a file with inferred types resolution, invalidate type reference directive resolution + if (containingFilePath.endsWith(ts.inferredTypesContainingFile)) { + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + } } }); }); @@ -99234,10 +99409,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99462,7 +99640,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99486,7 +99664,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99497,6 +99675,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99505,13 +99684,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -101403,30 +101586,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101434,7 +101612,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -103366,6 +103544,25 @@ var ts; return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } ts.documentSpansEqual = documentSpansEqual; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + ts.forEachUnique = forEachUnique; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -104641,8 +104838,10 @@ var ts; }); return { spans: spans, endOfLineState: 0 /* None */ }; function pushClassification(start, end, type) { + var length = end - start; + ts.Debug.assert(length > 0, "Classification had non-positive length of " + length); spans.push(start); - spans.push(end - start); + spans.push(length); spans.push(type); } } @@ -105061,8 +105260,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -105320,7 +105518,7 @@ var ts; var candidates = []; checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); @@ -106470,6 +106668,7 @@ var ts; var completionKind = 5 /* None */; var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; + // This also gets mutated in nested-functions after the return var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; @@ -106576,8 +106775,15 @@ var ts; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106594,8 +106800,15 @@ var ts; var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106897,7 +107110,7 @@ var ts; typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” + * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, * if and only if the the first can be imported (it may be excluded due to package.json filtering in @@ -106973,7 +107186,7 @@ var ts; // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -107162,7 +107375,7 @@ var ts; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 192 /* ObjectLiteralExpression */) { - var typeForObject = typeChecker.getContextualType(objectLikeContainer); + var typeForObject = typeChecker.getContextualType(objectLikeContainer, 4 /* Completion */); if (!typeForObject) return 2 /* Fail */; isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); @@ -107739,6 +107952,8 @@ var ts; return isFunctionLikeBodyKeyword(kind) || kind === 129 /* DeclareKeyword */ || kind === 134 /* ModuleKeyword */ + || kind === 144 /* TypeKeyword */ + || kind === 135 /* NamespaceKeyword */ || ts.isTypeKeyword(kind) && kind !== 145 /* UndefinedKeyword */; case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); @@ -110273,8 +110488,10 @@ var ts; || exportSpecifier.name.originalKeywordKind === 83 /* DefaultKeyword */; var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); - var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); - searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) { + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { @@ -111485,7 +111702,7 @@ var ts; // The property length will have two declarations of property length coming // from Array - Array and Array var documentationComment = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) @@ -111514,7 +111731,7 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); @@ -111551,24 +111768,6 @@ var ts; return comment === undefined ? s : s + " " + comment; } } - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEachUnique(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array.indexOf(array[i]) === i) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - } - return undefined; - } function getJSDocTagNameCompletions() { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -115583,7 +115782,7 @@ var ts; // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) { return declaration === (location.kind === 128 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { @@ -116490,8 +116689,8 @@ var ts; rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 95 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between @@ -119042,6 +119241,18 @@ var ts; cb(tracker); return tracker.getChanges(); }; + ChangeTracker.prototype.pushRaw = function (sourceFile, change) { + ts.Debug.assertEqual(sourceFile.fileName, change.fileName); + for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) { + var c = _a[_i]; + this.changes.push({ + kind: ChangeKind.Text, + sourceFile: sourceFile, + text: c.newText, + range: ts.createTextRangeFromSpan(c.span), + }); + } + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); }; @@ -119170,7 +119381,7 @@ var ts; endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) - return; // Function missing parentheses, give up + return false; // Function missing parentheses, give up // If no `)`, is an arrow function `x => x`, so use the end of the first parameter endNode = ts.first(node.parameters); } @@ -119179,6 +119390,7 @@ var ts; endNode = node.kind !== 241 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + return true; }; ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) { var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1; @@ -120805,20 +121017,20 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); }); }, }); @@ -120858,7 +121070,7 @@ var ts; } return errorCode; } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 103 /* ThisKeyword */) { return undefined; } @@ -120869,7 +121081,7 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); return parent; } if (ts.isPropertyAccessExpression(parent)) { @@ -120886,7 +121098,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); return symbol.valueDeclaration; } return undefined; @@ -120900,14 +121112,14 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); return param; } return undefined; @@ -120915,14 +121127,14 @@ var ts; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } return undefined; @@ -120937,12 +121149,12 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); } } - function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) { if (!ts.isIdentifier(parameterDeclaration.name)) { return; } @@ -120958,7 +121170,7 @@ var ts; for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host); + annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); } } if (needParens) @@ -120987,7 +121199,7 @@ var ts; ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), ]); } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); @@ -120998,11 +121210,11 @@ var ts; annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); } else { - annotate(changes, sourceFile, param, type, program, host); + annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); } } } - function annotate(changes, sourceFile, declaration, type, program, host) { + function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (ts.isInJSFile(sourceFile) && declaration.kind !== 157 /* PropertySignature */) { @@ -121014,11 +121226,32 @@ var ts; var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); addJSDocTags(changes, sourceFile, parent, [typeTag]); } - else { + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) { + var _a; + if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { + // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible + var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol; + // Symbol for the left-most thing after the dot + if (moduleSymbol) { + var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol; + var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences); + if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { + for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) { + var change = _b[_i]; + var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName)); + changes.pushRaw(file, change); + } + return true; + } + } + } + return false; + } function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { var signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { @@ -121710,7 +121943,7 @@ var ts; } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); } function addCandidateType(usage, type) { if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { @@ -123517,6 +123750,7 @@ var ts; var filteredCount = 0; var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); var allSourceFiles = program.getSourceFiles(); + var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) { if (sourceFile === undefined) { if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { @@ -123526,7 +123760,9 @@ var ts; filteredCount++; } } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + else if (sourceFile && + sourceFile !== from && + isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) { if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { cb(module); } @@ -123556,10 +123792,13 @@ var ts; * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ - function isImportablePath(fromPath, toPath) { + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); @@ -123604,6 +123843,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, + getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), }; var usesNodeCoreModules; return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; @@ -125179,14 +125419,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (sig.hasRestParameter) { + if (ts.signatureHasRestParameter(sig)) { someSigHasRestParameter = true; } - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) { maxArgsSignature = sig; } } - var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { @@ -129612,11 +129852,25 @@ var ts; TypeObject.prototype.isClass = function () { return !!(ts.getObjectFlags(this) & 1 /* Class */); }; + Object.defineProperty(TypeObject.prototype, "typeArguments", { + /** + * This polyfills `referenceType.typeArguments` for API consumers + */ + get: function () { + if (ts.getObjectFlags(this) & 4 /* Reference */) { + return this.checker.getTypeArguments(this); + } + return undefined; + }, + enumerable: true, + configurable: true + }); return TypeObject; }()); var SignatureObject = /** @class */ (function () { - function SignatureObject(checker) { + function SignatureObject(checker, flags) { this.checker = checker; + this.flags = flags; } SignatureObject.prototype.getDeclaration = function () { return this.declaration; @@ -129654,13 +129908,12 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + ts.forEachUnique(declarations, function (declaration) { var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - } + }); } return doc; } @@ -130541,12 +130794,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles) { - if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } // Signature help /** @@ -133695,16 +133947,31 @@ var ts; case 1: return this.containingProjects[0]; default: - // if this file belongs to multiple projects, the first configured project should be - // the default project; if no configured projects, the first external project should - // be the default project; otherwise the first inferred project should be the default. + // If this file belongs to multiple projects, below is the order in which default project is used + // - for open script info, its default configured project during opening is default if info is part of it + // - first configured project of which script info is not a source of project reference redirect + // - first configured project + // - first external project + // - first inferred project var firstExternalProject = void 0; var firstConfiguredProject = void 0; - for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { - var project = _a[_i]; + var firstNonSourceOfProjectReferenceRedirect = void 0; + var defaultConfiguredProject = void 0; + for (var index = 0; index < this.containingProjects.length; index++) { + var project = this.containingProjects[index]; if (project.projectKind === server.ProjectKind.Configured) { - if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) - return project; + if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) { + // If we havent found default configuredProject and + // its not the last one, find it and use that one if there + if (defaultConfiguredProject === undefined && + index !== this.containingProjects.length - 1) { + defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false; + } + if (defaultConfiguredProject === project) + return project; + if (!firstNonSourceOfProjectReferenceRedirect) + firstNonSourceOfProjectReferenceRedirect = project; + } if (!firstConfiguredProject) firstConfiguredProject = project; } @@ -133712,7 +133979,11 @@ var ts; firstExternalProject = project; } } - return firstConfiguredProject || firstExternalProject || this.containingProjects[0]; + return defaultConfiguredProject || + firstNonSourceOfProjectReferenceRedirect || + firstConfiguredProject || + firstExternalProject || + this.containingProjects[0]; } }; ScriptInfo.prototype.registerFileUpdate = function () { @@ -134122,6 +134393,10 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign(__assign({}, options), { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + /*@internal*/ + Project.prototype.getGlobalTypingsCacheLocation = function () { + return this.getGlobalCache(); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -136685,6 +136960,14 @@ var ts; } while (anySearchPathOk || isSearchPathInProjectRoot()); return undefined; }; + /*@internal*/ + ProjectService.prototype.findDefaultConfiguredProject = function (info) { + if (!info.isScriptOpen()) + return undefined; + var configFileName = this.getConfigFileNameForFile(info); + return configFileName && + this.findConfiguredProjectByProjectName(configFileName); + }; /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because diff --git a/lib/tsserverlibrary.d.ts b/lib/tsserverlibrary.d.ts index 5ad30ae8803..d5111cf8777 100644 --- a/lib/tsserverlibrary.d.ts +++ b/lib/tsserverlibrary.d.ts @@ -13,6 +13,12 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +declare namespace ts { + interface Map { + } + function createMapShim(): new () => Map; +} +//# sourceMappingURL=shims.d.ts.map declare namespace ts { const versionMajorMinor = "3.7"; /** The version of the TypeScript compiler release */ @@ -1964,6 +1970,8 @@ declare namespace ts { DiagnosticsPresent_OutputsSkipped = 1, DiagnosticsPresent_OutputsGenerated = 2, InvalidProject_OutputsSkipped = 3, + ProjectReferenceCycle_OutputsSkipped = 4, + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ProjectReferenceCycle_OutputsSkupped = 4 } export interface EmitResult { @@ -3169,6 +3177,7 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ @@ -4902,6 +4911,9 @@ declare namespace ts { isClassOrInterface(): this is InterfaceType; isClass(): this is InterfaceType; } + interface TypeReference { + typeArguments?: readonly Type[]; + } interface Signature { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; @@ -5068,7 +5080,7 @@ declare namespace ts { getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; dispose(): void; } @@ -5191,7 +5203,7 @@ declare namespace ts { } interface FileTextChanges { fileName: string; - textChanges: TextChange[]; + textChanges: readonly TextChange[]; isNewFile?: boolean; } interface CodeAction { @@ -6623,9 +6635,11 @@ declare namespace ts.server.protocol { interface DefinitionResponse extends Response { body?: FileSpanWithContext[]; } - interface DefinitionInfoAndBoundSpanReponse extends Response { + interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; } + /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ + type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; /** * Definition response message. Gives text range for definition. */ @@ -8288,6 +8302,12 @@ declare namespace ts.server.protocol { * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. */ readonly includeCompletionsWithInsertText?: boolean; + /** + * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled, + * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined + * values, with insertion text to replace preceding `.` tokens with `?.`. + */ + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; readonly lazyConfiguredProjectsFromExternalProject?: boolean; diff --git a/lib/tsserverlibrary.js b/lib/tsserverlibrary.js index 58981472463..2265d268040 100644 --- a/lib/tsserverlibrary.js +++ b/lib/tsserverlibrary.js @@ -87,67 +87,20 @@ var __rest = (this && this.__rest) || function (s, e) { } return t; }; +/* @internal */ var ts; (function (ts) { - // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. - // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.7"; - /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-beta"; -})(ts || (ts = {})); -(function (ts) { - /* @internal */ - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; - } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ - function createMap() { - return new ts.MapCtr(); - } - ts.createMap = createMap; - function createMapFromEntries(entries) { - var map = createMap(); - for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { - var _a = entries_1[_i], key = _a[0], value = _a[1]; - map.set(key, value); + function createMapShim() { + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; } - return map; - } - ts.createMapFromEntries = createMapFromEntries; - function createMapFromTemplate(template) { - var map = new ts.MapCtr(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { var MapIterator = /** @class */ (function () { function MapIterator(currentEntry, selector) { this.currentEntry = currentEntry; @@ -283,7 +236,75 @@ var ts; return class_1; }()); } - ts.shimMap = shimMap; + ts.createMapShim = createMapShim; +})(ts || (ts = {})); +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.7"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".0-beta"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; + } + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ + function createMap() { + return new ts.Map(); + } + ts.createMap = createMap; + /** Create a new map from an array of entries. */ + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ + function createMapFromTemplate(template) { + var map = new ts.Map(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; function length(array) { return array ? array.length : 0; } @@ -1865,20 +1886,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2279,6 +2286,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2322,6 +2356,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2485,8 +2533,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3381,6 +3427,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3436,6 +3483,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3445,6 +3494,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3886,6 +3943,18 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsOptionalCall"] = 4] = "IsOptionalCall"; + // We do not propagate `IsOptionalCall` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -5057,6 +5126,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5195,6 +5273,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5639,6 +5718,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5666,7 +6412,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5874,7 +6620,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5909,6 +6655,7 @@ var ts; Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"), An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), + Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -6036,7 +6783,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6209,6 +6955,8 @@ var ts; Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), + Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), + Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -6719,6 +7467,7 @@ var ts; The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), 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."), @@ -9054,7 +9803,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9110,13 +9859,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9923,6 +10665,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10735,7 +11482,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10747,7 +11494,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10966,7 +11713,7 @@ var ts; ts.idText(expr.expression.expression) === "Object" && ts.idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && - isBindableStaticNameExpression(expr.arguments[0]); + isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { @@ -11074,9 +11821,11 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } // F.G...x = expr @@ -12402,7 +13151,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12924,6 +13673,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13442,20 +14208,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13482,7 +14234,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14547,11 +15299,21 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return ts.isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15913,7 +16675,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16188,273 +16955,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16471,15 +16971,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16489,229 +16989,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16730,10 +17009,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16809,7 +17084,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16871,7 +17146,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16900,7 +17175,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16910,8 +17185,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16938,8 +17213,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16961,14 +17236,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16985,9 +17260,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17152,14 +17427,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17202,36 +17472,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18742,7 +18982,12 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var isReservedWord = scanner.isReservedWord(); + var msgArg = scanner.getTokenText(); + var defaultMessage = isReservedWord ? + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : + ts.Diagnostics.Identifier_expected; + return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -25069,6 +25314,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -26061,6 +26315,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26069,104 +26324,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26485,7 +26643,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26506,12 +26664,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26688,6 +26846,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27138,7 +27325,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28922,7 +29109,11 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } + var flowNodeCreated = initFlowNode; var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28986,6 +29177,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29341,7 +29535,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29353,7 +29547,7 @@ var ts; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; + flowNodeCreated = initFlowNode; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29522,9 +29716,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29564,9 +29755,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29623,10 +29813,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29647,7 +29837,7 @@ var ts; } if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { + if (!ts.isExpressionOfOptionalChainRoot(expression)) { return unreachableFlow; } } @@ -29872,7 +30062,7 @@ var ts; // as possible antecedents of the start of the `catch` or `finally` blocks. // Don't bother intercepting the call if there's no finally or catch block that needs the information if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; + flowNodeCreated = function (node) { return (tryPriors.push(node), initFlowNode(node)); }; } bind(node.tryBlock); flowNodeCreated = oldFlowNodeCreated; @@ -29936,7 +30126,7 @@ var ts; // // extra edges that we inject allows to control this behavior // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); @@ -30003,7 +30193,7 @@ var ts; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30593,7 +30783,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -31016,6 +31206,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31235,7 +31427,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31324,6 +31517,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31398,7 +31595,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32899,12 +33096,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33043,9 +33234,6 @@ var ts; var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33164,9 +33352,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33215,7 +33403,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33400,10 +33588,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33556,7 +33744,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33566,7 +33754,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -34754,7 +34942,12 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } } } else if (hasSyntheticDefault) { @@ -34858,7 +35051,12 @@ var ts; } } else { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + if (moduleSymbol.exports && moduleSymbol.exports.has("default" /* Default */)) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } } return symbol; @@ -35034,7 +35232,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35997,7 +36195,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36852,7 +37050,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37621,7 +37819,7 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & 16 /* Function */)); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); @@ -37832,7 +38030,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37844,7 +38046,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -38113,7 +38315,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38536,7 +38738,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -39296,7 +39498,7 @@ var ts; // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39364,7 +39566,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39447,7 +39649,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39683,6 +39887,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39713,7 +39918,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40550,8 +40755,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40559,15 +40764,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40579,13 +40782,17 @@ var ts; result.mapper = undefined; return result; } + function getOptionalCallSignature(signature) { + return signatureIsOptionalCall(signature) ? signature : + (signature.optionalCallSignatureCache || (signature.optionalCallSignatureCache = createOptionalCallSignature(signature))); + } function createOptionalCallSignature(signature) { var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= 4 /* IsOptionalCall */; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40610,7 +40817,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40774,11 +40981,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40951,7 +41156,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41891,7 +42096,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41922,7 +42127,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41948,9 +42153,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42093,8 +42300,8 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signatureIsOptionalCall(signature)) { + type = addOptionalTypeMarker(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42150,7 +42357,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42524,7 +42731,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42537,18 +42744,25 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function fakes special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = ts.isVariableDeclaration(decl) + && decl.initializer + && ts.isCallExpression(decl.initializer) + && ts.isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ true) + && valueType.symbol; + if (isRequireAlias) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -44089,7 +44303,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44504,7 +44718,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45392,7 +45606,7 @@ var ts; */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** @@ -48077,37 +48291,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } function propagateOptionalTypeMarker(type, wasOptional) { return wasOptional ? addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48742,10 +48938,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48845,10 +49038,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48900,6 +49090,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48965,6 +49161,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -48994,6 +49202,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49025,15 +49243,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49054,14 +49269,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49069,10 +49282,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -49450,6 +49660,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49570,8 +49789,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49940,8 +50159,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50022,9 +50241,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50037,6 +50265,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50052,6 +50287,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50071,8 +50311,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50306,6 +50555,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50324,7 +50576,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50395,17 +50647,27 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } + else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { + return unreachableNeverType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50547,6 +50809,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50595,6 +50860,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50618,6 +50891,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50665,8 +50947,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50674,9 +50962,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50709,6 +50994,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50841,6 +51130,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50913,39 +51205,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -52006,18 +52287,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52376,7 +52661,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52591,8 +52876,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -53589,8 +53874,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53598,22 +53883,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53622,10 +53919,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53633,8 +53936,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53687,7 +53989,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -54009,7 +54311,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54025,7 +54335,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54126,7 +54436,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54137,7 +54447,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, isOptionalCall ? getOptionalCallSignature(signature) : signature); } } function isSpreadArgument(arg) { @@ -54432,7 +54742,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54659,7 +54981,7 @@ var ts; if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); } } if (min < argCount && argCount < max) { @@ -54985,34 +55307,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55093,7 +55415,17 @@ var ts; } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var isOptional; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + isOptional = nonOptionalType !== funcType; + funcType = nonOptionalType; + } + else { + isOptional = false; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55315,8 +55647,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55475,9 +55807,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55510,7 +55840,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55891,7 +56221,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55908,11 +56238,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55947,7 +56277,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55956,7 +56286,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55968,14 +56298,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -55992,7 +56322,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56025,7 +56355,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56033,7 +56363,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56438,7 +56768,7 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); returnOnlyType.objectFlags |= 1048576 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; @@ -56771,8 +57101,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57771,7 +58101,18 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; + var isOptional = void 0; + var funcType = void 0; + if (ts.isCallChain(expr)) { + funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + isOptional = funcType !== nonOptionalType; + funcType = checkNonNullType(nonOptionalType, expr.expression); + } + else { + isOptional = false; + funcType = checkNonNullExpression(expr.expression); + } var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); @@ -58028,7 +58369,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59203,7 +59544,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59260,7 +59601,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59300,8 +59641,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61076,10 +61417,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61100,6 +61438,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61651,15 +61992,13 @@ var ts; } } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62165,22 +62504,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62310,7 +62633,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62377,7 +62700,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64683,10 +65006,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65569,7 +65892,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65639,6 +65962,18 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; + function signatureIsOptionalCall(s) { + return !!(s.flags & 4 /* IsOptionalCall */); + } + ts.signatureIsOptionalCall = signatureIsOptionalCall; })(ts || (ts = {})); var ts; (function (ts) { @@ -66572,7 +66907,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66610,7 +66947,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66644,7 +66983,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67246,7 +67587,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -68346,8 +68687,11 @@ var ts; (texts || (texts = [])).push(prependNode); break; case "internal" /* Internal */: - if (stripInternal) + if (stripInternal) { + if (!texts) + texts = []; break; + } // falls through case "text" /* Text */: (texts || (texts = [])).push(createUnparsedNode(section, node)); @@ -69769,7 +70113,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -74212,8 +74556,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -75644,7 +75988,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -87659,6 +88003,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89430,7 +89775,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92184,8 +92533,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94455,6 +94804,8 @@ var ts; return resolutions; } ts.loadWithLocalCache = loadWithLocalCache; + /* @internal */ + ts.inferredTypesContainingFile = "__inferred type names__.ts"; /** * Determines if program structure is upto date or needs to be recreated */ @@ -94707,7 +95058,7 @@ var ts; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); - var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -96445,9 +96796,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97492,6 +97840,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98222,7 +98571,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98258,33 +98607,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -98828,6 +99150,10 @@ var ts; // 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); + // When its a file with inferred types resolution, invalidate type reference directive resolution + if (containingFilePath.endsWith(ts.inferredTypesContainingFile)) { + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + } } }); }); @@ -99233,10 +99559,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99461,7 +99790,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99485,7 +99814,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99496,6 +99825,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99504,13 +99834,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -101402,30 +101736,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101433,7 +101762,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -103728,6 +104057,25 @@ var ts; return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } ts.documentSpansEqual = documentSpansEqual; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + ts.forEachUnique = forEachUnique; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -105003,8 +105351,10 @@ var ts; }); return { spans: spans, endOfLineState: 0 /* None */ }; function pushClassification(start, end, type) { + var length = end - start; + ts.Debug.assert(length > 0, "Classification had non-positive length of " + length); spans.push(start); - spans.push(end - start); + spans.push(length); spans.push(type); } } @@ -105423,8 +105773,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -105682,7 +106031,7 @@ var ts; var candidates = []; checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); @@ -106832,6 +107181,7 @@ var ts; var completionKind = 5 /* None */; var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; + // This also gets mutated in nested-functions after the return var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; @@ -106938,8 +107288,15 @@ var ts; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106956,8 +107313,15 @@ var ts; var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -107259,7 +107623,7 @@ var ts; typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” + * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, * if and only if the the first can be imported (it may be excluded due to package.json filtering in @@ -107335,7 +107699,7 @@ var ts; // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -107524,7 +107888,7 @@ var ts; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 192 /* ObjectLiteralExpression */) { - var typeForObject = typeChecker.getContextualType(objectLikeContainer); + var typeForObject = typeChecker.getContextualType(objectLikeContainer, 4 /* Completion */); if (!typeForObject) return 2 /* Fail */; isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); @@ -108101,6 +108465,8 @@ var ts; return isFunctionLikeBodyKeyword(kind) || kind === 129 /* DeclareKeyword */ || kind === 134 /* ModuleKeyword */ + || kind === 144 /* TypeKeyword */ + || kind === 135 /* NamespaceKeyword */ || ts.isTypeKeyword(kind) && kind !== 145 /* UndefinedKeyword */; case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); @@ -110635,8 +111001,10 @@ var ts; || exportSpecifier.name.originalKeywordKind === 83 /* DefaultKeyword */; var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); - var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); - searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) { + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { @@ -111847,7 +112215,7 @@ var ts; // The property length will have two declarations of property length coming // from Array - Array and Array var documentationComment = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) @@ -111876,7 +112244,7 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); @@ -111913,24 +112281,6 @@ var ts; return comment === undefined ? s : s + " " + comment; } } - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEachUnique(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array.indexOf(array[i]) === i) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - } - return undefined; - } function getJSDocTagNameCompletions() { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -115945,7 +116295,7 @@ var ts; // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) { return declaration === (location.kind === 128 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { @@ -116852,8 +117202,8 @@ var ts; rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 95 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between @@ -119404,6 +119754,18 @@ var ts; cb(tracker); return tracker.getChanges(); }; + ChangeTracker.prototype.pushRaw = function (sourceFile, change) { + ts.Debug.assertEqual(sourceFile.fileName, change.fileName); + for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) { + var c = _a[_i]; + this.changes.push({ + kind: ChangeKind.Text, + sourceFile: sourceFile, + text: c.newText, + range: ts.createTextRangeFromSpan(c.span), + }); + } + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); }; @@ -119532,7 +119894,7 @@ var ts; endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) - return; // Function missing parentheses, give up + return false; // Function missing parentheses, give up // If no `)`, is an arrow function `x => x`, so use the end of the first parameter endNode = ts.first(node.parameters); } @@ -119541,6 +119903,7 @@ var ts; endNode = node.kind !== 241 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + return true; }; ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) { var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1; @@ -121167,20 +121530,20 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); }); }, }); @@ -121220,7 +121583,7 @@ var ts; } return errorCode; } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 103 /* ThisKeyword */) { return undefined; } @@ -121231,7 +121594,7 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); return parent; } if (ts.isPropertyAccessExpression(parent)) { @@ -121248,7 +121611,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); return symbol.valueDeclaration; } return undefined; @@ -121262,14 +121625,14 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); return param; } return undefined; @@ -121277,14 +121640,14 @@ var ts; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } return undefined; @@ -121299,12 +121662,12 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); } } - function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) { if (!ts.isIdentifier(parameterDeclaration.name)) { return; } @@ -121320,7 +121683,7 @@ var ts; for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host); + annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); } } if (needParens) @@ -121349,7 +121712,7 @@ var ts; ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), ]); } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); @@ -121360,11 +121723,11 @@ var ts; annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); } else { - annotate(changes, sourceFile, param, type, program, host); + annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); } } } - function annotate(changes, sourceFile, declaration, type, program, host) { + function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (ts.isInJSFile(sourceFile) && declaration.kind !== 157 /* PropertySignature */) { @@ -121376,11 +121739,32 @@ var ts; var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); addJSDocTags(changes, sourceFile, parent, [typeTag]); } - else { + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) { + var _a; + if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { + // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible + var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol; + // Symbol for the left-most thing after the dot + if (moduleSymbol) { + var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol; + var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences); + if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { + for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) { + var change = _b[_i]; + var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName)); + changes.pushRaw(file, change); + } + return true; + } + } + } + return false; + } function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { var signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { @@ -122072,7 +122456,7 @@ var ts; } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); } function addCandidateType(usage, type) { if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { @@ -123879,6 +124263,7 @@ var ts; var filteredCount = 0; var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); var allSourceFiles = program.getSourceFiles(); + var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) { if (sourceFile === undefined) { if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { @@ -123888,7 +124273,9 @@ var ts; filteredCount++; } } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + else if (sourceFile && + sourceFile !== from && + isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) { if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { cb(module); } @@ -123918,10 +124305,13 @@ var ts; * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ - function isImportablePath(fromPath, toPath) { + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); @@ -123966,6 +124356,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, + getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), }; var usesNodeCoreModules; return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; @@ -125541,14 +125932,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (sig.hasRestParameter) { + if (ts.signatureHasRestParameter(sig)) { someSigHasRestParameter = true; } - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) { maxArgsSignature = sig; } } - var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { @@ -129974,11 +130365,25 @@ var ts; TypeObject.prototype.isClass = function () { return !!(ts.getObjectFlags(this) & 1 /* Class */); }; + Object.defineProperty(TypeObject.prototype, "typeArguments", { + /** + * This polyfills `referenceType.typeArguments` for API consumers + */ + get: function () { + if (ts.getObjectFlags(this) & 4 /* Reference */) { + return this.checker.getTypeArguments(this); + } + return undefined; + }, + enumerable: true, + configurable: true + }); return TypeObject; }()); var SignatureObject = /** @class */ (function () { - function SignatureObject(checker) { + function SignatureObject(checker, flags) { this.checker = checker; + this.flags = flags; } SignatureObject.prototype.getDeclaration = function () { return this.declaration; @@ -130016,13 +130421,12 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + ts.forEachUnique(declarations, function (declaration) { var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - } + }); } return doc; } @@ -130903,12 +131307,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles) { - if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } // Signature help /** @@ -133694,16 +134097,31 @@ var ts; case 1: return this.containingProjects[0]; default: - // if this file belongs to multiple projects, the first configured project should be - // the default project; if no configured projects, the first external project should - // be the default project; otherwise the first inferred project should be the default. + // If this file belongs to multiple projects, below is the order in which default project is used + // - for open script info, its default configured project during opening is default if info is part of it + // - first configured project of which script info is not a source of project reference redirect + // - first configured project + // - first external project + // - first inferred project var firstExternalProject = void 0; var firstConfiguredProject = void 0; - for (var _i = 0, _a = this.containingProjects; _i < _a.length; _i++) { - var project = _a[_i]; + var firstNonSourceOfProjectReferenceRedirect = void 0; + var defaultConfiguredProject = void 0; + for (var index = 0; index < this.containingProjects.length; index++) { + var project = this.containingProjects[index]; if (project.projectKind === server.ProjectKind.Configured) { - if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) - return project; + if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) { + // If we havent found default configuredProject and + // its not the last one, find it and use that one if there + if (defaultConfiguredProject === undefined && + index !== this.containingProjects.length - 1) { + defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false; + } + if (defaultConfiguredProject === project) + return project; + if (!firstNonSourceOfProjectReferenceRedirect) + firstNonSourceOfProjectReferenceRedirect = project; + } if (!firstConfiguredProject) firstConfiguredProject = project; } @@ -133711,7 +134129,11 @@ var ts; firstExternalProject = project; } } - return firstConfiguredProject || firstExternalProject || this.containingProjects[0]; + return defaultConfiguredProject || + firstNonSourceOfProjectReferenceRedirect || + firstConfiguredProject || + firstExternalProject || + this.containingProjects[0]; } }; ScriptInfo.prototype.registerFileUpdate = function () { @@ -134121,6 +134543,10 @@ var ts; Project.prototype.installPackage = function (options) { return this.typingsCache.installPackage(__assign(__assign({}, options), { projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) })); }; + /*@internal*/ + Project.prototype.getGlobalTypingsCacheLocation = function () { + return this.getGlobalCache(); + }; Object.defineProperty(Project.prototype, "typingsCache", { get: function () { return this.projectService.typingsCache; @@ -136684,6 +137110,14 @@ var ts; } while (anySearchPathOk || isSearchPathInProjectRoot()); return undefined; }; + /*@internal*/ + ProjectService.prototype.findDefaultConfiguredProject = function (info) { + if (!info.isScriptOpen()) + return undefined; + var configFileName = this.getConfigFileNameForFile(info); + return configFileName && + this.findConfiguredProjectByProjectName(configFileName); + }; /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because diff --git a/lib/typescript.d.ts b/lib/typescript.d.ts index 7bf245876e5..adc1703eae2 100644 --- a/lib/typescript.d.ts +++ b/lib/typescript.d.ts @@ -13,6 +13,12 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +declare namespace ts { + interface Map { + } + function createMapShim(): new () => Map; +} +//# sourceMappingURL=shims.d.ts.map declare namespace ts { const versionMajorMinor = "3.7"; /** The version of the TypeScript compiler release */ @@ -1964,6 +1970,8 @@ declare namespace ts { DiagnosticsPresent_OutputsSkipped = 1, DiagnosticsPresent_OutputsGenerated = 2, InvalidProject_OutputsSkipped = 3, + ProjectReferenceCycle_OutputsSkipped = 4, + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ProjectReferenceCycle_OutputsSkupped = 4 } export interface EmitResult { @@ -3169,6 +3177,7 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ @@ -4902,6 +4911,9 @@ declare namespace ts { isClassOrInterface(): this is InterfaceType; isClass(): this is InterfaceType; } + interface TypeReference { + typeArguments?: readonly Type[]; + } interface Signature { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; @@ -5068,7 +5080,7 @@ declare namespace ts { getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; dispose(): void; } @@ -5191,7 +5203,7 @@ declare namespace ts { } interface FileTextChanges { fileName: string; - textChanges: TextChange[]; + textChanges: readonly TextChange[]; isNewFile?: boolean; } interface CodeAction { diff --git a/lib/typescript.js b/lib/typescript.js index 1a793952c14..2a675f9c927 100644 --- a/lib/typescript.js +++ b/lib/typescript.js @@ -76,67 +76,20 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +/* @internal */ var ts; (function (ts) { - // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. - // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.7"; - /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-beta"; -})(ts || (ts = {})); -(function (ts) { - /* @internal */ - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; - } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ - function createMap() { - return new ts.MapCtr(); - } - ts.createMap = createMap; - function createMapFromEntries(entries) { - var map = createMap(); - for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { - var _a = entries_1[_i], key = _a[0], value = _a[1]; - map.set(key, value); + function createMapShim() { + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; } - return map; - } - ts.createMapFromEntries = createMapFromEntries; - function createMapFromTemplate(template) { - var map = new ts.MapCtr(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { var MapIterator = /** @class */ (function () { function MapIterator(currentEntry, selector) { this.currentEntry = currentEntry; @@ -272,7 +225,75 @@ var ts; return class_1; }()); } - ts.shimMap = shimMap; + ts.createMapShim = createMapShim; +})(ts || (ts = {})); +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.7"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".0-beta"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; + } + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ + function createMap() { + return new ts.Map(); + } + ts.createMap = createMap; + /** Create a new map from an array of entries. */ + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ + function createMapFromTemplate(template) { + var map = new ts.Map(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; function length(array) { return array ? array.length : 0; } @@ -1854,20 +1875,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2268,6 +2275,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2311,6 +2345,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2474,8 +2522,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3370,6 +3416,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3425,6 +3472,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3434,6 +3483,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3875,6 +3932,18 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsOptionalCall"] = 4] = "IsOptionalCall"; + // We do not propagate `IsOptionalCall` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -5046,6 +5115,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5184,6 +5262,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5628,6 +5707,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5655,7 +6401,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5863,7 +6609,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5898,6 +6644,7 @@ var ts; Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"), An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), + Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -6025,7 +6772,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6198,6 +6944,8 @@ var ts; Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), + Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), + Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -6708,6 +7456,7 @@ var ts; The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), 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."), @@ -9043,7 +9792,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9099,13 +9848,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9912,6 +10654,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10724,7 +11471,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10736,7 +11483,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10955,7 +11702,7 @@ var ts; ts.idText(expr.expression.expression) === "Object" && ts.idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && - isBindableStaticNameExpression(expr.arguments[0]); + isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { @@ -11063,9 +11810,11 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } // F.G...x = expr @@ -12391,7 +13140,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12913,6 +13662,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13431,20 +14197,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13471,7 +14223,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14536,11 +15288,21 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return ts.isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15902,7 +16664,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16177,273 +16944,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16460,15 +16960,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16478,229 +16978,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16719,10 +16998,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16798,7 +17073,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16860,7 +17135,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16889,7 +17164,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16899,8 +17174,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16927,8 +17202,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16950,14 +17225,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16974,9 +17249,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17141,14 +17416,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17191,36 +17461,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18731,7 +18971,12 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var isReservedWord = scanner.isReservedWord(); + var msgArg = scanner.getTokenText(); + var defaultMessage = isReservedWord ? + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : + ts.Diagnostics.Identifier_expected; + return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -25058,6 +25303,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -26050,6 +26304,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26058,104 +26313,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26474,7 +26632,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26495,12 +26653,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26677,6 +26835,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27127,7 +27314,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28911,7 +29098,11 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } + var flowNodeCreated = initFlowNode; var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28975,6 +29166,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29330,7 +29524,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29342,7 +29536,7 @@ var ts; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; + flowNodeCreated = initFlowNode; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29511,9 +29705,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29553,9 +29744,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29612,10 +29802,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29636,7 +29826,7 @@ var ts; } if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { + if (!ts.isExpressionOfOptionalChainRoot(expression)) { return unreachableFlow; } } @@ -29861,7 +30051,7 @@ var ts; // as possible antecedents of the start of the `catch` or `finally` blocks. // Don't bother intercepting the call if there's no finally or catch block that needs the information if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; + flowNodeCreated = function (node) { return (tryPriors.push(node), initFlowNode(node)); }; } bind(node.tryBlock); flowNodeCreated = oldFlowNodeCreated; @@ -29925,7 +30115,7 @@ var ts; // // extra edges that we inject allows to control this behavior // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); @@ -29992,7 +30182,7 @@ var ts; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30582,7 +30772,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -31005,6 +31195,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31224,7 +31416,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31313,6 +31506,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31387,7 +31584,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32888,12 +33085,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33032,9 +33223,6 @@ var ts; var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33153,9 +33341,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33204,7 +33392,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33389,10 +33577,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33545,7 +33733,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33555,7 +33743,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -34743,7 +34931,12 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } } } else if (hasSyntheticDefault) { @@ -34847,7 +35040,12 @@ var ts; } } else { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + if (moduleSymbol.exports && moduleSymbol.exports.has("default" /* Default */)) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } } return symbol; @@ -35023,7 +35221,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35986,7 +36184,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36841,7 +37039,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37610,7 +37808,7 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & 16 /* Function */)); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); @@ -37821,7 +38019,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37833,7 +38035,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -38102,7 +38304,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38525,7 +38727,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -39285,7 +39487,7 @@ var ts; // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39353,7 +39555,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39436,7 +39638,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39672,6 +39876,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39702,7 +39907,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40539,8 +40744,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40548,15 +40753,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40568,13 +40771,17 @@ var ts; result.mapper = undefined; return result; } + function getOptionalCallSignature(signature) { + return signatureIsOptionalCall(signature) ? signature : + (signature.optionalCallSignatureCache || (signature.optionalCallSignatureCache = createOptionalCallSignature(signature))); + } function createOptionalCallSignature(signature) { var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= 4 /* IsOptionalCall */; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40599,7 +40806,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40763,11 +40970,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40940,7 +41145,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41880,7 +42085,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41911,7 +42116,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41937,9 +42142,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42082,8 +42289,8 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signatureIsOptionalCall(signature)) { + type = addOptionalTypeMarker(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42139,7 +42346,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42513,7 +42720,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42526,18 +42733,25 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function fakes special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = ts.isVariableDeclaration(decl) + && decl.initializer + && ts.isCallExpression(decl.initializer) + && ts.isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ true) + && valueType.symbol; + if (isRequireAlias) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -44078,7 +44292,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44493,7 +44707,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45381,7 +45595,7 @@ var ts; */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** @@ -48066,37 +48280,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } function propagateOptionalTypeMarker(type, wasOptional) { return wasOptional ? addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48731,10 +48927,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48834,10 +49027,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48889,6 +49079,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48954,6 +49150,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -48983,6 +49191,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49014,15 +49232,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49043,14 +49258,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49058,10 +49271,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -49439,6 +49649,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49559,8 +49778,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49929,8 +50148,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50011,9 +50230,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50026,6 +50254,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50041,6 +50276,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50060,8 +50300,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50295,6 +50544,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50313,7 +50565,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50384,17 +50636,27 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } + else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { + return unreachableNeverType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50536,6 +50798,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50584,6 +50849,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50607,6 +50880,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50654,8 +50936,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50663,9 +50951,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50698,6 +50983,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50830,6 +51119,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50902,39 +51194,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -51995,18 +52276,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52365,7 +52650,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52580,8 +52865,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -53578,8 +53863,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53587,22 +53872,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53611,10 +53908,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53622,8 +53925,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53676,7 +53978,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -53998,7 +54300,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54014,7 +54324,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54115,7 +54425,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54126,7 +54436,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, isOptionalCall ? getOptionalCallSignature(signature) : signature); } } function isSpreadArgument(arg) { @@ -54421,7 +54731,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54648,7 +54970,7 @@ var ts; if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); } } if (min < argCount && argCount < max) { @@ -54974,34 +55296,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55082,7 +55404,17 @@ var ts; } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var isOptional; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + isOptional = nonOptionalType !== funcType; + funcType = nonOptionalType; + } + else { + isOptional = false; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55304,8 +55636,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55464,9 +55796,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55499,7 +55829,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55880,7 +56210,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55897,11 +56227,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55936,7 +56266,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55945,7 +56275,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55957,14 +56287,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -55981,7 +56311,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56014,7 +56344,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56022,7 +56352,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56427,7 +56757,7 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); returnOnlyType.objectFlags |= 1048576 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; @@ -56760,8 +57090,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57760,7 +58090,18 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; + var isOptional = void 0; + var funcType = void 0; + if (ts.isCallChain(expr)) { + funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + isOptional = funcType !== nonOptionalType; + funcType = checkNonNullType(nonOptionalType, expr.expression); + } + else { + isOptional = false; + funcType = checkNonNullExpression(expr.expression); + } var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); @@ -58017,7 +58358,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59192,7 +59533,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59249,7 +59590,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59289,8 +59630,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61065,10 +61406,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61089,6 +61427,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61640,15 +61981,13 @@ var ts; } } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62154,22 +62493,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62299,7 +62622,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62366,7 +62689,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64672,10 +64995,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65558,7 +65881,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65628,6 +65951,18 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; + function signatureIsOptionalCall(s) { + return !!(s.flags & 4 /* IsOptionalCall */); + } + ts.signatureIsOptionalCall = signatureIsOptionalCall; })(ts || (ts = {})); var ts; (function (ts) { @@ -66561,7 +66896,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66599,7 +66936,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66633,7 +66972,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67235,7 +67576,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -68335,8 +68676,11 @@ var ts; (texts || (texts = [])).push(prependNode); break; case "internal" /* Internal */: - if (stripInternal) + if (stripInternal) { + if (!texts) + texts = []; break; + } // falls through case "text" /* Text */: (texts || (texts = [])).push(createUnparsedNode(section, node)); @@ -69758,7 +70102,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -74201,8 +74545,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -75633,7 +75977,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -87648,6 +87992,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89419,7 +89764,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92173,8 +92522,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94444,6 +94793,8 @@ var ts; return resolutions; } ts.loadWithLocalCache = loadWithLocalCache; + /* @internal */ + ts.inferredTypesContainingFile = "__inferred type names__.ts"; /** * Determines if program structure is upto date or needs to be recreated */ @@ -94696,7 +95047,7 @@ var ts; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); - var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -96434,9 +96785,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97481,6 +97829,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98211,7 +98560,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98247,33 +98596,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -98817,6 +99139,10 @@ var ts; // 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); + // When its a file with inferred types resolution, invalidate type reference directive resolution + if (containingFilePath.endsWith(ts.inferredTypesContainingFile)) { + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + } } }); }); @@ -99222,10 +99548,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99450,7 +99779,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99474,7 +99803,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99485,6 +99814,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99493,13 +99823,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -101391,30 +101725,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101422,7 +101751,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -103717,6 +104046,25 @@ var ts; return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } ts.documentSpansEqual = documentSpansEqual; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + ts.forEachUnique = forEachUnique; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -104992,8 +105340,10 @@ var ts; }); return { spans: spans, endOfLineState: 0 /* None */ }; function pushClassification(start, end, type) { + var length = end - start; + ts.Debug.assert(length > 0, "Classification had non-positive length of " + length); spans.push(start); - spans.push(end - start); + spans.push(length); spans.push(type); } } @@ -105412,8 +105762,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -105671,7 +106020,7 @@ var ts; var candidates = []; checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); @@ -106821,6 +107170,7 @@ var ts; var completionKind = 5 /* None */; var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; + // This also gets mutated in nested-functions after the return var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; @@ -106927,8 +107277,15 @@ var ts; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106945,8 +107302,15 @@ var ts; var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -107248,7 +107612,7 @@ var ts; typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” + * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, * if and only if the the first can be imported (it may be excluded due to package.json filtering in @@ -107324,7 +107688,7 @@ var ts; // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -107513,7 +107877,7 @@ var ts; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 192 /* ObjectLiteralExpression */) { - var typeForObject = typeChecker.getContextualType(objectLikeContainer); + var typeForObject = typeChecker.getContextualType(objectLikeContainer, 4 /* Completion */); if (!typeForObject) return 2 /* Fail */; isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); @@ -108090,6 +108454,8 @@ var ts; return isFunctionLikeBodyKeyword(kind) || kind === 129 /* DeclareKeyword */ || kind === 134 /* ModuleKeyword */ + || kind === 144 /* TypeKeyword */ + || kind === 135 /* NamespaceKeyword */ || ts.isTypeKeyword(kind) && kind !== 145 /* UndefinedKeyword */; case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); @@ -110624,8 +110990,10 @@ var ts; || exportSpecifier.name.originalKeywordKind === 83 /* DefaultKeyword */; var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); - var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); - searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) { + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { @@ -111836,7 +112204,7 @@ var ts; // The property length will have two declarations of property length coming // from Array - Array and Array var documentationComment = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) @@ -111865,7 +112233,7 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); @@ -111902,24 +112270,6 @@ var ts; return comment === undefined ? s : s + " " + comment; } } - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEachUnique(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array.indexOf(array[i]) === i) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - } - return undefined; - } function getJSDocTagNameCompletions() { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -115934,7 +116284,7 @@ var ts; // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) { return declaration === (location.kind === 128 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { @@ -116841,8 +117191,8 @@ var ts; rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 95 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between @@ -119393,6 +119743,18 @@ var ts; cb(tracker); return tracker.getChanges(); }; + ChangeTracker.prototype.pushRaw = function (sourceFile, change) { + ts.Debug.assertEqual(sourceFile.fileName, change.fileName); + for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) { + var c = _a[_i]; + this.changes.push({ + kind: ChangeKind.Text, + sourceFile: sourceFile, + text: c.newText, + range: ts.createTextRangeFromSpan(c.span), + }); + } + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); }; @@ -119521,7 +119883,7 @@ var ts; endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) - return; // Function missing parentheses, give up + return false; // Function missing parentheses, give up // If no `)`, is an arrow function `x => x`, so use the end of the first parameter endNode = ts.first(node.parameters); } @@ -119530,6 +119892,7 @@ var ts; endNode = node.kind !== 241 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + return true; }; ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) { var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1; @@ -121156,20 +121519,20 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); }); }, }); @@ -121209,7 +121572,7 @@ var ts; } return errorCode; } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 103 /* ThisKeyword */) { return undefined; } @@ -121220,7 +121583,7 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); return parent; } if (ts.isPropertyAccessExpression(parent)) { @@ -121237,7 +121600,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); return symbol.valueDeclaration; } return undefined; @@ -121251,14 +121614,14 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); return param; } return undefined; @@ -121266,14 +121629,14 @@ var ts; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } return undefined; @@ -121288,12 +121651,12 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); } } - function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) { if (!ts.isIdentifier(parameterDeclaration.name)) { return; } @@ -121309,7 +121672,7 @@ var ts; for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host); + annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); } } if (needParens) @@ -121338,7 +121701,7 @@ var ts; ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), ]); } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); @@ -121349,11 +121712,11 @@ var ts; annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); } else { - annotate(changes, sourceFile, param, type, program, host); + annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); } } } - function annotate(changes, sourceFile, declaration, type, program, host) { + function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (ts.isInJSFile(sourceFile) && declaration.kind !== 157 /* PropertySignature */) { @@ -121365,11 +121728,32 @@ var ts; var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); addJSDocTags(changes, sourceFile, parent, [typeTag]); } - else { + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) { + var _a; + if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { + // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible + var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol; + // Symbol for the left-most thing after the dot + if (moduleSymbol) { + var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol; + var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences); + if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { + for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) { + var change = _b[_i]; + var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName)); + changes.pushRaw(file, change); + } + return true; + } + } + } + return false; + } function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { var signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { @@ -122061,7 +122445,7 @@ var ts; } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); } function addCandidateType(usage, type) { if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { @@ -123868,6 +124252,7 @@ var ts; var filteredCount = 0; var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); var allSourceFiles = program.getSourceFiles(); + var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) { if (sourceFile === undefined) { if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { @@ -123877,7 +124262,9 @@ var ts; filteredCount++; } } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + else if (sourceFile && + sourceFile !== from && + isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) { if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { cb(module); } @@ -123907,10 +124294,13 @@ var ts; * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ - function isImportablePath(fromPath, toPath) { + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); @@ -123955,6 +124345,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, + getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), }; var usesNodeCoreModules; return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; @@ -125530,14 +125921,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (sig.hasRestParameter) { + if (ts.signatureHasRestParameter(sig)) { someSigHasRestParameter = true; } - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) { maxArgsSignature = sig; } } - var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { @@ -129963,11 +130354,25 @@ var ts; TypeObject.prototype.isClass = function () { return !!(ts.getObjectFlags(this) & 1 /* Class */); }; + Object.defineProperty(TypeObject.prototype, "typeArguments", { + /** + * This polyfills `referenceType.typeArguments` for API consumers + */ + get: function () { + if (ts.getObjectFlags(this) & 4 /* Reference */) { + return this.checker.getTypeArguments(this); + } + return undefined; + }, + enumerable: true, + configurable: true + }); return TypeObject; }()); var SignatureObject = /** @class */ (function () { - function SignatureObject(checker) { + function SignatureObject(checker, flags) { this.checker = checker; + this.flags = flags; } SignatureObject.prototype.getDeclaration = function () { return this.declaration; @@ -130005,13 +130410,12 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + ts.forEachUnique(declarations, function (declaration) { var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - } + }); } return doc; } @@ -130892,12 +131296,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles) { - if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } // Signature help /** diff --git a/lib/typescriptServices.d.ts b/lib/typescriptServices.d.ts index 65a08122899..6c8954496f3 100644 --- a/lib/typescriptServices.d.ts +++ b/lib/typescriptServices.d.ts @@ -13,6 +13,12 @@ See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ +declare namespace ts { + interface Map { + } + function createMapShim(): new () => Map; +} +//# sourceMappingURL=shims.d.ts.map declare namespace ts { const versionMajorMinor = "3.7"; /** The version of the TypeScript compiler release */ @@ -1964,6 +1970,8 @@ declare namespace ts { DiagnosticsPresent_OutputsSkipped = 1, DiagnosticsPresent_OutputsGenerated = 2, InvalidProject_OutputsSkipped = 3, + ProjectReferenceCycle_OutputsSkipped = 4, + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ProjectReferenceCycle_OutputsSkupped = 4 } export interface EmitResult { @@ -3169,6 +3177,7 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ @@ -4902,6 +4911,9 @@ declare namespace ts { isClassOrInterface(): this is InterfaceType; isClass(): this is InterfaceType; } + interface TypeReference { + typeArguments?: readonly Type[]; + } interface Signature { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; @@ -5068,7 +5080,7 @@ declare namespace ts { getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; dispose(): void; } @@ -5191,7 +5203,7 @@ declare namespace ts { } interface FileTextChanges { fileName: string; - textChanges: TextChange[]; + textChanges: readonly TextChange[]; isNewFile?: boolean; } interface CodeAction { diff --git a/lib/typescriptServices.js b/lib/typescriptServices.js index 2942410dd4c..08a9fa3df44 100644 --- a/lib/typescriptServices.js +++ b/lib/typescriptServices.js @@ -76,67 +76,20 @@ var __extends = (this && this.__extends) || (function () { d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); +/* @internal */ var ts; (function (ts) { - // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. - // If changing the text in this section, be sure to test `configureNightly` too. - ts.versionMajorMinor = "3.7"; - /** The version of the TypeScript compiler release */ - ts.version = ts.versionMajorMinor + ".0-beta"; -})(ts || (ts = {})); -(function (ts) { - /* @internal */ - var Comparison; - (function (Comparison) { - Comparison[Comparison["LessThan"] = -1] = "LessThan"; - Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; - Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; - })(Comparison = ts.Comparison || (ts.Comparison = {})); -})(ts || (ts = {})); -/* @internal */ -(function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; - } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ - function createMap() { - return new ts.MapCtr(); - } - ts.createMap = createMap; - function createMapFromEntries(entries) { - var map = createMap(); - for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { - var _a = entries_1[_i], key = _a[0], value = _a[1]; - map.set(key, value); + function createMapShim() { + /** Create a MapLike with good performance. */ + function createDictionaryObject() { + var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + return map; } - return map; - } - ts.createMapFromEntries = createMapFromEntries; - function createMapFromTemplate(template) { - var map = new ts.MapCtr(); - // Copies keys/values from template. Note that for..in will not throw if - // template is undefined, and instead will just exit the loop. - for (var key in template) { - if (hasOwnProperty.call(template, key)) { - map.set(key, template[key]); - } - } - return map; - } - ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { var MapIterator = /** @class */ (function () { function MapIterator(currentEntry, selector) { this.currentEntry = currentEntry; @@ -272,7 +225,75 @@ var ts; return class_1; }()); } - ts.shimMap = shimMap; + ts.createMapShim = createMapShim; +})(ts || (ts = {})); +var ts; +(function (ts) { + // WARNING: The script `configureNightly.ts` uses a regexp to parse out these values. + // If changing the text in this section, be sure to test `configureNightly` too. + ts.versionMajorMinor = "3.7"; + /** The version of the TypeScript compiler release */ + ts.version = ts.versionMajorMinor + ".0-beta"; +})(ts || (ts = {})); +(function (ts) { + /* @internal */ + var Comparison; + (function (Comparison) { + Comparison[Comparison["LessThan"] = -1] = "LessThan"; + Comparison[Comparison["EqualTo"] = 0] = "EqualTo"; + Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan"; + })(Comparison = ts.Comparison || (ts.Comparison = {})); +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; + } + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ + function createMap() { + return new ts.Map(); + } + ts.createMap = createMap; + /** Create a new map from an array of entries. */ + function createMapFromEntries(entries) { + var map = createMap(); + for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { + var _a = entries_1[_i], key = _a[0], value = _a[1]; + map.set(key, value); + } + return map; + } + ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ + function createMapFromTemplate(template) { + var map = new ts.Map(); + // Copies keys/values from template. Note that for..in will not throw if + // template is undefined, and instead will just exit the loop. + for (var key in template) { + if (hasOwnProperty.call(template, key)) { + map.set(key, template[key]); + } + } + return map; + } + ts.createMapFromTemplate = createMapFromTemplate; function length(array) { return array ? array.length : 0; } @@ -1854,20 +1875,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2268,6 +2275,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2311,6 +2345,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2474,8 +2522,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3370,6 +3416,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3425,6 +3472,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3434,6 +3483,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3875,6 +3932,18 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsOptionalCall"] = 4] = "IsOptionalCall"; + // We do not propagate `IsOptionalCall` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -5046,6 +5115,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5184,6 +5262,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5628,6 +5707,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5655,7 +6401,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5863,7 +6609,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5898,6 +6644,7 @@ var ts; Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"), An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), + Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -6025,7 +6772,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6198,6 +6944,8 @@ var ts; Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), + Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), + Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -6708,6 +7456,7 @@ var ts; The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), 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."), @@ -9043,7 +9792,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9099,13 +9848,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9912,6 +10654,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10724,7 +11471,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10736,7 +11483,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10955,7 +11702,7 @@ var ts; ts.idText(expr.expression.expression) === "Object" && ts.idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && - isBindableStaticNameExpression(expr.arguments[0]); + isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { @@ -11063,9 +11810,11 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } // F.G...x = expr @@ -12391,7 +13140,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12913,6 +13662,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13431,20 +14197,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13471,7 +14223,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14536,11 +15288,21 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return ts.isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15902,7 +16664,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16177,273 +16944,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16460,15 +16960,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16478,229 +16978,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16719,10 +16998,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16798,7 +17073,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16860,7 +17135,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16889,7 +17164,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16899,8 +17174,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16927,8 +17202,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16950,14 +17225,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16974,9 +17249,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17141,14 +17416,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17191,36 +17461,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18731,7 +18971,12 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var isReservedWord = scanner.isReservedWord(); + var msgArg = scanner.getTokenText(); + var defaultMessage = isReservedWord ? + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : + ts.Diagnostics.Identifier_expected; + return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -25058,6 +25303,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -26050,6 +26304,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26058,104 +26313,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26474,7 +26632,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26495,12 +26653,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26677,6 +26835,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27127,7 +27314,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28911,7 +29098,11 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } + var flowNodeCreated = initFlowNode; var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28975,6 +29166,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29330,7 +29524,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29342,7 +29536,7 @@ var ts; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; + flowNodeCreated = initFlowNode; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29511,9 +29705,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29553,9 +29744,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29612,10 +29802,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29636,7 +29826,7 @@ var ts; } if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { + if (!ts.isExpressionOfOptionalChainRoot(expression)) { return unreachableFlow; } } @@ -29861,7 +30051,7 @@ var ts; // as possible antecedents of the start of the `catch` or `finally` blocks. // Don't bother intercepting the call if there's no finally or catch block that needs the information if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; + flowNodeCreated = function (node) { return (tryPriors.push(node), initFlowNode(node)); }; } bind(node.tryBlock); flowNodeCreated = oldFlowNodeCreated; @@ -29925,7 +30115,7 @@ var ts; // // extra edges that we inject allows to control this behavior // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); @@ -29992,7 +30182,7 @@ var ts; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30582,7 +30772,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -31005,6 +31195,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31224,7 +31416,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31313,6 +31506,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31387,7 +31584,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32888,12 +33085,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33032,9 +33223,6 @@ var ts; var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33153,9 +33341,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33204,7 +33392,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33389,10 +33577,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33545,7 +33733,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33555,7 +33743,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -34743,7 +34931,12 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } } } else if (hasSyntheticDefault) { @@ -34847,7 +35040,12 @@ var ts; } } else { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + if (moduleSymbol.exports && moduleSymbol.exports.has("default" /* Default */)) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } } return symbol; @@ -35023,7 +35221,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35986,7 +36184,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36841,7 +37039,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37610,7 +37808,7 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & 16 /* Function */)); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); @@ -37821,7 +38019,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37833,7 +38035,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -38102,7 +38304,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38525,7 +38727,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -39285,7 +39487,7 @@ var ts; // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39353,7 +39555,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39436,7 +39638,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39672,6 +39876,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39702,7 +39907,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40539,8 +40744,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40548,15 +40753,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40568,13 +40771,17 @@ var ts; result.mapper = undefined; return result; } + function getOptionalCallSignature(signature) { + return signatureIsOptionalCall(signature) ? signature : + (signature.optionalCallSignatureCache || (signature.optionalCallSignatureCache = createOptionalCallSignature(signature))); + } function createOptionalCallSignature(signature) { var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= 4 /* IsOptionalCall */; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40599,7 +40806,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40763,11 +40970,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40940,7 +41145,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41880,7 +42085,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41911,7 +42116,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41937,9 +42142,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42082,8 +42289,8 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signatureIsOptionalCall(signature)) { + type = addOptionalTypeMarker(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42139,7 +42346,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42513,7 +42720,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42526,18 +42733,25 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function fakes special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = ts.isVariableDeclaration(decl) + && decl.initializer + && ts.isCallExpression(decl.initializer) + && ts.isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ true) + && valueType.symbol; + if (isRequireAlias) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -44078,7 +44292,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44493,7 +44707,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45381,7 +45595,7 @@ var ts; */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** @@ -48066,37 +48280,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } function propagateOptionalTypeMarker(type, wasOptional) { return wasOptional ? addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48731,10 +48927,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48834,10 +49027,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48889,6 +49079,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48954,6 +49150,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -48983,6 +49191,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49014,15 +49232,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49043,14 +49258,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49058,10 +49271,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -49439,6 +49649,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49559,8 +49778,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49929,8 +50148,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50011,9 +50230,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50026,6 +50254,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50041,6 +50276,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50060,8 +50300,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50295,6 +50544,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50313,7 +50565,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50384,17 +50636,27 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } + else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { + return unreachableNeverType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50536,6 +50798,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50584,6 +50849,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50607,6 +50880,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50654,8 +50936,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50663,9 +50951,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50698,6 +50983,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50830,6 +51119,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50902,39 +51194,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -51995,18 +52276,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52365,7 +52650,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52580,8 +52865,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -53578,8 +53863,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53587,22 +53872,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53611,10 +53908,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53622,8 +53925,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53676,7 +53978,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -53998,7 +54300,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54014,7 +54324,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54115,7 +54425,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54126,7 +54436,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, isOptionalCall ? getOptionalCallSignature(signature) : signature); } } function isSpreadArgument(arg) { @@ -54421,7 +54731,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54648,7 +54970,7 @@ var ts; if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); } } if (min < argCount && argCount < max) { @@ -54974,34 +55296,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55082,7 +55404,17 @@ var ts; } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var isOptional; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + isOptional = nonOptionalType !== funcType; + funcType = nonOptionalType; + } + else { + isOptional = false; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55304,8 +55636,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55464,9 +55796,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55499,7 +55829,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55880,7 +56210,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55897,11 +56227,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55936,7 +56266,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55945,7 +56275,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55957,14 +56287,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -55981,7 +56311,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56014,7 +56344,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56022,7 +56352,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56427,7 +56757,7 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); returnOnlyType.objectFlags |= 1048576 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; @@ -56760,8 +57090,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57760,7 +58090,18 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; + var isOptional = void 0; + var funcType = void 0; + if (ts.isCallChain(expr)) { + funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + isOptional = funcType !== nonOptionalType; + funcType = checkNonNullType(nonOptionalType, expr.expression); + } + else { + isOptional = false; + funcType = checkNonNullExpression(expr.expression); + } var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); @@ -58017,7 +58358,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59192,7 +59533,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59249,7 +59590,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59289,8 +59630,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61065,10 +61406,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61089,6 +61427,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61640,15 +61981,13 @@ var ts; } } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62154,22 +62493,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62299,7 +62622,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62366,7 +62689,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64672,10 +64995,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65558,7 +65881,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65628,6 +65951,18 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; + function signatureIsOptionalCall(s) { + return !!(s.flags & 4 /* IsOptionalCall */); + } + ts.signatureIsOptionalCall = signatureIsOptionalCall; })(ts || (ts = {})); var ts; (function (ts) { @@ -66561,7 +66896,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66599,7 +66936,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66633,7 +66972,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67235,7 +67576,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -68335,8 +68676,11 @@ var ts; (texts || (texts = [])).push(prependNode); break; case "internal" /* Internal */: - if (stripInternal) + if (stripInternal) { + if (!texts) + texts = []; break; + } // falls through case "text" /* Text */: (texts || (texts = [])).push(createUnparsedNode(section, node)); @@ -69758,7 +70102,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -74201,8 +74545,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -75633,7 +75977,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -87648,6 +87992,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89419,7 +89764,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92173,8 +92522,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94444,6 +94793,8 @@ var ts; return resolutions; } ts.loadWithLocalCache = loadWithLocalCache; + /* @internal */ + ts.inferredTypesContainingFile = "__inferred type names__.ts"; /** * Determines if program structure is upto date or needs to be recreated */ @@ -94696,7 +95047,7 @@ var ts; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); - var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -96434,9 +96785,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97481,6 +97829,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98211,7 +98560,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98247,33 +98596,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -98817,6 +99139,10 @@ var ts; // 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); + // When its a file with inferred types resolution, invalidate type reference directive resolution + if (containingFilePath.endsWith(ts.inferredTypesContainingFile)) { + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + } } }); }); @@ -99222,10 +99548,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99450,7 +99779,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99474,7 +99803,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99485,6 +99814,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99493,13 +99823,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -101391,30 +101725,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101422,7 +101751,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; @@ -103717,6 +104046,25 @@ var ts; return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } ts.documentSpansEqual = documentSpansEqual; + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + function forEachUnique(array, callback) { + if (array) { + for (var i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + var result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } + ts.forEachUnique = forEachUnique; })(ts || (ts = {})); // Display-part writer helpers /* @internal */ @@ -104992,8 +105340,10 @@ var ts; }); return { spans: spans, endOfLineState: 0 /* None */ }; function pushClassification(start, end, type) { + var length = end - start; + ts.Debug.assert(length > 0, "Classification had non-positive length of " + length); spans.push(start); - spans.push(end - start); + spans.push(length); spans.push(type); } } @@ -105412,8 +105762,7 @@ var ts; return 25 /* bigintLiteral */; } else if (tokenKind === 10 /* StringLiteral */) { - // TODO: GH#18217 - return token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; + return token && token.parent.kind === 271 /* JsxAttribute */ ? 24 /* jsxAttributeStringLiteralValue */ : 6 /* stringLiteral */; } else if (tokenKind === 13 /* RegularExpressionLiteral */) { // TODO: we should get another classification type for these literals. @@ -105671,7 +106020,7 @@ var ts; var candidates = []; checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); var types = ts.flatMap(candidates, function (candidate) { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) + if (!ts.signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; var type = checker.getParameterType(candidate, argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & 4 /* String */); @@ -106821,6 +107170,7 @@ var ts; var completionKind = 5 /* None */; var isNewIdentifierLocation = false; var keywordFilters = 0 /* None */; + // This also gets mutated in nested-functions after the return var symbols = []; var symbolToOriginInfoMap = []; var symbolToSortTextMap = []; @@ -106927,8 +107277,15 @@ var ts; var type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -106945,8 +107302,15 @@ var ts; var type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); var insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + var canCorrectToQuestionDot = isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & 32768 /* AwaitContext */), insertQuestionDot); } @@ -107248,7 +107612,7 @@ var ts; typeChecker.getExportsOfModule(sym).some(function (e) { return symbolCanBeReferencedAtTypeLocation(e, seenModules); }); } /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” + * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, * if and only if the the first can be imported (it may be excluded due to package.json filtering in @@ -107324,7 +107688,7 @@ var ts; // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. if (resolvedModuleSymbol !== moduleSymbol && - ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) { + ts.every(resolvedModuleSymbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator && !ts.findAncestor(d, ts.isGlobalScopeAugmentation); })) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } for (var _i = 0, _a = typeChecker.getExportsOfModule(moduleSymbol); _i < _a.length; _i++) { @@ -107513,7 +107877,7 @@ var ts; var typeMembers; var existingMembers; if (objectLikeContainer.kind === 192 /* ObjectLiteralExpression */) { - var typeForObject = typeChecker.getContextualType(objectLikeContainer); + var typeForObject = typeChecker.getContextualType(objectLikeContainer, 4 /* Completion */); if (!typeForObject) return 2 /* Fail */; isNewIdentifierLocation = ts.hasIndexSignature(typeForObject); @@ -108090,6 +108454,8 @@ var ts; return isFunctionLikeBodyKeyword(kind) || kind === 129 /* DeclareKeyword */ || kind === 134 /* ModuleKeyword */ + || kind === 144 /* TypeKeyword */ + || kind === 135 /* NamespaceKeyword */ || ts.isTypeKeyword(kind) && kind !== 145 /* UndefinedKeyword */; case 5 /* FunctionLikeBodyKeywords */: return isFunctionLikeBodyKeyword(kind); @@ -110624,8 +110990,10 @@ var ts; || exportSpecifier.name.originalKeywordKind === 83 /* DefaultKeyword */; var exportKind = isDefaultExport ? 1 /* Default */ : 0 /* Named */; var exportSymbol = ts.Debug.assertDefined(exportSpecifier.symbol); - var exportInfo = ts.Debug.assertDefined(FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker)); - searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + var exportInfo = FindAllReferences.getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) { + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. if (search.comingFrom !== 1 /* Export */ && exportDeclaration.moduleSpecifier && !propertyName && !isForRenameWithPrefixAndSuffixText(state.options)) { @@ -111836,7 +112204,7 @@ var ts; // The property length will have two declarations of property length coming // from Array - Array and Array var documentationComment = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = getCommentHavingNodes(declaration); _i < _a.length; _i++) { var comment = _a[_i].comment; if (comment === undefined) @@ -111865,7 +112233,7 @@ var ts; function getJsDocTagsFromDeclarations(declarations) { // Only collect doc comments from duplicate declarations once. var tags = []; - forEachUnique(declarations, function (declaration) { + ts.forEachUnique(declarations, function (declaration) { for (var _i = 0, _a = ts.getJSDocTags(declaration); _i < _a.length; _i++) { var tag = _a[_i]; tags.push({ name: tag.tagName.text, text: getCommentText(tag) }); @@ -111902,24 +112270,6 @@ var ts; return comment === undefined ? s : s + " " + comment; } } - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEachUnique(array, callback) { - if (array) { - for (var i = 0; i < array.length; i++) { - if (array.indexOf(array[i]) === i) { - var result = callback(array[i], i); - if (result) { - return result; - } - } - } - } - return undefined; - } function getJSDocTagNameCompletions() { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = ts.map(jsDocTagNames, function (tagName) { return { @@ -115934,7 +116284,7 @@ var ts; // get the signature from the declaration and write it var functionDeclaration_1 = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - var locationIsSymbolDeclaration = ts.find(symbol.declarations, function (declaration) { + var locationIsSymbolDeclaration = symbol.declarations && ts.find(symbol.declarations, function (declaration) { return declaration === (location.kind === 128 /* ConstructorKeyword */ ? functionDeclaration_1.parent : functionDeclaration_1); }); if (locationIsSymbolDeclaration) { @@ -116841,8 +117191,8 @@ var ts; rule("SpaceAfterQuestionMarkInConditionalOperator", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext, isConditionalOperatorContext], 4 /* InsertSpace */), // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", 57 /* QuestionToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceBeforeDot", anyToken, 24 /* DotToken */, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), - rule("NoSpaceAfterDot", 24 /* DotToken */, anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceBeforeDot", anyToken, [24 /* DotToken */, 28 /* QuestionDotToken */], [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), + rule("NoSpaceAfterDot", [24 /* DotToken */, 28 /* QuestionDotToken */], anyToken, [isNonJsxSameLineTokenContext], 16 /* DeleteSpace */), rule("NoSpaceBetweenImportParenInImportType", 95 /* ImportKeyword */, 20 /* OpenParenToken */, [isNonJsxSameLineTokenContext, isImportTypeContext], 16 /* DeleteSpace */), // Special handling of unary operators. // Prefix operators generally shouldn't have a space between @@ -119393,6 +119743,18 @@ var ts; cb(tracker); return tracker.getChanges(); }; + ChangeTracker.prototype.pushRaw = function (sourceFile, change) { + ts.Debug.assertEqual(sourceFile.fileName, change.fileName); + for (var _i = 0, _a = change.textChanges; _i < _a.length; _i++) { + var c = _a[_i]; + this.changes.push({ + kind: ChangeKind.Text, + sourceFile: sourceFile, + text: c.newText, + range: ts.createTextRangeFromSpan(c.span), + }); + } + }; ChangeTracker.prototype.deleteRange = function (sourceFile, range) { this.changes.push({ kind: ChangeKind.Remove, sourceFile: sourceFile, range: range }); }; @@ -119521,7 +119883,7 @@ var ts; endNode = ts.findChildOfKind(node, 21 /* CloseParenToken */, sourceFile); if (!endNode) { if (!ts.isArrowFunction(node)) - return; // Function missing parentheses, give up + return false; // Function missing parentheses, give up // If no `)`, is an arrow function `x => x`, so use the end of the first parameter endNode = ts.first(node.parameters); } @@ -119530,6 +119892,7 @@ var ts; endNode = node.kind !== 241 /* VariableDeclaration */ && node.questionToken ? node.questionToken : node.name; } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + return true; }; ChangeTracker.prototype.tryInsertThisTypeAnnotation = function (sourceFile, node, type) { var start = ts.findChildOfKind(node, 20 /* OpenParenToken */, sourceFile).getStart(sourceFile) + 1; @@ -121156,20 +121519,20 @@ var ts; codefix.registerCodeFix({ errorCodes: errorCodes, getCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, start = context.span.start, errorCode = context.errorCode, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var token = ts.getTokenAtPosition(sourceFile, start); var declaration; - var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host); }); + var changes = ts.textChanges.ChangeTracker.with(context, function (changes) { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ ts.returnTrue, host, formatContext, preferences); }); var name = declaration && ts.getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [codefix.createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, ts.Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions: function (context) { - var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host; + var sourceFile = context.sourceFile, program = context.program, cancellationToken = context.cancellationToken, host = context.host, formatContext = context.formatContext, preferences = context.preferences; var markSeen = ts.nodeSeenTracker(); return codefix.codeFixAll(context, errorCodes, function (changes, err) { - doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + doChange(changes, sourceFile, ts.getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); }); }, }); @@ -121209,7 +121572,7 @@ var ts; } return errorCode; } - function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host) { + function doChange(changes, sourceFile, token, errorCode, program, cancellationToken, markSeen, host, formatContext, preferences) { if (!ts.isParameterPropertyModifier(token.kind) && token.kind !== 75 /* Identifier */ && token.kind !== 25 /* DotDotDotToken */ && token.kind !== 103 /* ThisKeyword */) { return undefined; } @@ -121220,7 +121583,7 @@ var ts; case ts.Diagnostics.Member_0_implicitly_has_an_1_type.code: case ts.Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((ts.isVariableDeclaration(parent) && markSeen(parent)) || ts.isPropertyDeclaration(parent) || ts.isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); return parent; } if (ts.isPropertyAccessExpression(parent)) { @@ -121237,7 +121600,7 @@ var ts; case ts.Diagnostics.Variable_0_implicitly_has_an_1_type.code: { var symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); return symbol.valueDeclaration; } return undefined; @@ -121251,14 +121614,14 @@ var ts; // Parameter declarations case ts.Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } // falls through case ts.Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { var param = ts.cast(parent, ts.isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); return param; } return undefined; @@ -121266,14 +121629,14 @@ var ts; case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (ts.isGetAccessorDeclaration(containingFunction) && ts.isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); return containingFunction; } return undefined; // Set Accessor declarations case ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (ts.isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } return undefined; @@ -121288,12 +121651,12 @@ var ts; return ts.Debug.fail(String(errorCode)); } } - function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken) { + function annotateVariableDeclaration(changes, sourceFile, declaration, program, host, cancellationToken, formatContext, preferences) { if (ts.isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); } } - function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken) { + function annotateParameters(changes, sourceFile, parameterDeclaration, containingFunction, program, host, cancellationToken, formatContext, preferences) { if (!ts.isIdentifier(parameterDeclaration.name)) { return; } @@ -121309,7 +121672,7 @@ var ts; for (var _i = 0, parameterInferences_1 = parameterInferences; _i < parameterInferences_1.length; _i++) { var _a = parameterInferences_1[_i], declaration = _a.declaration, type = _a.type; if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host); + annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); } } if (needParens) @@ -121338,7 +121701,7 @@ var ts; ts.createJSDocThisTag(ts.createJSDocTypeExpression(typeNode)), ]); } - function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken) { + function annotateSetAccessor(changes, sourceFile, setAccessorDeclaration, program, host, cancellationToken, formatContext, preferences) { var param = ts.firstOrUndefined(setAccessorDeclaration.parameters); if (param && ts.isIdentifier(setAccessorDeclaration.name) && ts.isIdentifier(param.name)) { var type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); @@ -121349,11 +121712,11 @@ var ts; annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type: type }], program, host); } else { - annotate(changes, sourceFile, param, type, program, host); + annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); } } } - function annotate(changes, sourceFile, declaration, type, program, host) { + function annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences) { var typeNode = ts.getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (ts.isInJSFile(sourceFile) && declaration.kind !== 157 /* PropertySignature */) { @@ -121365,11 +121728,32 @@ var ts; var typeTag = ts.isGetAccessorDeclaration(declaration) ? ts.createJSDocReturnTag(typeExpression, "") : ts.createJSDocTypeTag(typeExpression, ""); addJSDocTags(changes, sourceFile, parent, [typeTag]); } - else { + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } + function tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences) { + var _a; + if (ts.isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { + // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible + var moduleSymbol = (_a = ts.find(type.symbol.declarations, function (d) { return !!d.getSourceFile().externalModuleIndicator; })) === null || _a === void 0 ? void 0 : _a.getSourceFile().symbol; + // Symbol for the left-most thing after the dot + if (moduleSymbol) { + var symbol = ts.getFirstIdentifier(typeNode.qualifier).symbol; + var action = codefix.getImportCompletionAction(symbol, moduleSymbol, sourceFile, symbol.name, host, program, formatContext, declaration.pos, preferences); + if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, ts.createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { + for (var _i = 0, _b = action.codeAction.changes; _i < _b.length; _i++) { + var change = _b[_i]; + var file = sourceFile.fileName === change.fileName ? sourceFile : ts.Debug.assertDefined(program.getSourceFile(change.fileName)); + changes.pushRaw(file, change); + } + return true; + } + } + } + return false; + } function annotateJSDocParameters(changes, sourceFile, parameterInferences, program, host) { var signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { @@ -122061,7 +122445,7 @@ var ts; } var returnType = combineFromUsage(combineUsages(calls.map(function (call) { return call.return_; }))); // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return checker.createSignature(/*declaration*/ undefined, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, 0 /* None */); } function addCandidateType(usage, type) { if (type && !(type.flags & 1 /* Any */) && !(type.flags & 131072 /* Never */)) { @@ -123868,6 +124252,7 @@ var ts; var filteredCount = 0; var packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); var allSourceFiles = program.getSourceFiles(); + var globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); forEachExternalModule(program.getTypeChecker(), allSourceFiles, function (module, sourceFile) { if (sourceFile === undefined) { if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { @@ -123877,7 +124262,9 @@ var ts; filteredCount++; } } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + else if (sourceFile && + sourceFile !== from && + isImportablePath(from.fileName, sourceFile.fileName, ts.hostGetCanonicalFileName(host), globalTypingsCache)) { if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { cb(module); } @@ -123907,10 +124294,13 @@ var ts; * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ - function isImportablePath(fromPath, toPath) { + function isImportablePath(fromPath, toPath, getCanonicalFileName, globalCachePath) { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. var toNodeModules = ts.forEachAncestorDirectory(toPath, function (ancestor) { return ts.getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined; }); - return toNodeModules === undefined || ts.startsWith(fromPath, ts.getDirectoryPath(toNodeModules)); + var toNodeModulesParent = toNodeModules && ts.getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || ts.startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && ts.startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } function moduleSymbolToValidIdentifier(moduleSymbol, target) { return moduleSpecifierToValidIdentifier(ts.removeFileExtension(ts.stripQuotes(moduleSymbol.name)), target); @@ -123955,6 +124345,7 @@ var ts; readFile: ts.maybeBind(host, host.readFile), useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames), getProbableSymlinks: ts.maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, + getGlobalTypingsCacheLocation: ts.maybeBind(host, host.getGlobalTypingsCacheLocation), }; var usesNodeCoreModules; return { allowsImportingAmbientModule: allowsImportingAmbientModule, allowsImportingSourceFile: allowsImportingSourceFile, allowsImportingSpecifier: allowsImportingSpecifier }; @@ -125530,14 +125921,14 @@ var ts; for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) { var sig = signatures_2[_i]; minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (sig.hasRestParameter) { + if (ts.signatureHasRestParameter(sig)) { someSigHasRestParameter = true; } - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!ts.signatureHasRestParameter(sig) || ts.signatureHasRestParameter(maxArgsSignature))) { maxArgsSignature = sig; } } - var maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + var maxNonRestArgs = maxArgsSignature.parameters.length - (ts.signatureHasRestParameter(maxArgsSignature) ? 1 : 0); var maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(function (symbol) { return symbol.name; }); var parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); if (someSigHasRestParameter) { @@ -129963,11 +130354,25 @@ var ts; TypeObject.prototype.isClass = function () { return !!(ts.getObjectFlags(this) & 1 /* Class */); }; + Object.defineProperty(TypeObject.prototype, "typeArguments", { + /** + * This polyfills `referenceType.typeArguments` for API consumers + */ + get: function () { + if (ts.getObjectFlags(this) & 4 /* Reference */) { + return this.checker.getTypeArguments(this); + } + return undefined; + }, + enumerable: true, + configurable: true + }); return TypeObject; }()); var SignatureObject = /** @class */ (function () { - function SignatureObject(checker) { + function SignatureObject(checker, flags) { this.checker = checker; + this.flags = flags; } SignatureObject.prototype.getDeclaration = function () { return this.declaration; @@ -130005,13 +130410,12 @@ var ts; return ts.emptyArray; var doc = ts.JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) { - var declaration = declarations_4[_i]; + ts.forEachUnique(declarations, function (declaration) { var inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(ts.lineBreakPart(), doc); - } + }); } return doc; } @@ -130892,12 +131296,11 @@ var ts; var sourceFiles = fileName ? [getValidSourceFile(fileName)] : program.getSourceFiles(); return ts.NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName, emitOnlyDtsFiles) { - if (emitOnlyDtsFiles === void 0) { emitOnlyDtsFiles = false; } + function getEmitOutput(fileName, emitOnlyDtsFiles, forceDtsEmit) { synchronizeHostData(); var sourceFile = getValidSourceFile(fileName); var customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return ts.getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + return ts.getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } // Signature help /** diff --git a/lib/typingsInstaller.js b/lib/typingsInstaller.js index 855c65d7bbd..041ffd366ac 100644 --- a/lib/typingsInstaller.js +++ b/lib/typingsInstaller.js @@ -96,22 +96,32 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - ts.emptyArray = []; - /** Create a MapLike with good performance. */ - function createDictionaryObject() { - var map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - return map; + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + function tryGetNativeMap() { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; } - /** Create a new map. If a template object is provided, the map will copy entries from it. */ + ts.tryGetNativeMap = tryGetNativeMap; +})(ts || (ts = {})); +/* @internal */ +(function (ts) { + ts.emptyArray = []; + ts.Map = ts.tryGetNativeMap() || (function () { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof ts.createMapShim === "function") { + return ts.createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); + /** Create a new map. */ function createMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createMap = createMap; + /** Create a new map from an array of entries. */ function createMapFromEntries(entries) { var map = createMap(); for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) { @@ -121,8 +131,9 @@ var ts; return map; } ts.createMapFromEntries = createMapFromEntries; + /** Create a new map from a template object is provided, the map will copy entries from it. */ function createMapFromTemplate(template) { - var map = new ts.MapCtr(); + var map = new ts.Map(); // Copies keys/values from template. Note that for..in will not throw if // template is undefined, and instead will just exit the loop. for (var key in template) { @@ -133,147 +144,6 @@ var ts; return map; } ts.createMapFromTemplate = createMapFromTemplate; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - ts.MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - // Keep the class inside a function so it doesn't get compiled if it's not used. - function shimMap() { - var MapIterator = /** @class */ (function () { - function MapIterator(currentEntry, selector) { - this.currentEntry = currentEntry; - this.selector = selector; - } - MapIterator.prototype.next = function () { - // Navigate to the next entry. - while (this.currentEntry) { - var skipNext = !!this.currentEntry.skipNext; - this.currentEntry = this.currentEntry.nextEntry; - if (!skipNext) { - break; - } - } - if (this.currentEntry) { - return { value: this.selector(this.currentEntry.key, this.currentEntry.value), done: false }; - } - else { - return { value: undefined, done: true }; - } - }; - return MapIterator; - }()); - return /** @class */ (function () { - function class_1() { - this.data = createDictionaryObject(); - this.size = 0; - // Create a first (stub) map entry that will not contain a key - // and value but serves as starting point for iterators. - this.firstEntry = {}; - // When the map is empty, the last entry is the same as the - // first one. - this.lastEntry = this.firstEntry; - } - class_1.prototype.get = function (key) { - var entry = this.data[key]; - return entry && entry.value; - }; - class_1.prototype.set = function (key, value) { - if (!this.has(key)) { - this.size++; - // Create a new entry that will be appended at the - // end of the linked list. - var newEntry = { - key: key, - value: value - }; - this.data[key] = newEntry; - // Adjust the references. - var previousLastEntry = this.lastEntry; - previousLastEntry.nextEntry = newEntry; - newEntry.previousEntry = previousLastEntry; - this.lastEntry = newEntry; - } - else { - this.data[key].value = value; - } - return this; - }; - class_1.prototype.has = function (key) { - // eslint-disable-next-line no-in-operator - return key in this.data; - }; - class_1.prototype.delete = function (key) { - if (this.has(key)) { - this.size--; - var entry = this.data[key]; - delete this.data[key]; - // Adjust the linked list references of the neighbor entries. - var previousEntry = entry.previousEntry; - previousEntry.nextEntry = entry.nextEntry; - if (entry.nextEntry) { - entry.nextEntry.previousEntry = previousEntry; - } - // When the deleted entry was the last one, we need to - // adjust the lastEntry reference. - if (this.lastEntry === entry) { - this.lastEntry = previousEntry; - } - // Adjust the forward reference of the deleted entry - // in case an iterator still references it. This allows us - // to throw away the entry, but when an active iterator - // (which points to the current entry) continues, it will - // navigate to the entry that originally came before the - // current one and skip it. - entry.previousEntry = undefined; - entry.nextEntry = previousEntry; - entry.skipNext = true; - return true; - } - return false; - }; - class_1.prototype.clear = function () { - this.data = createDictionaryObject(); - this.size = 0; - // Reset the linked list. Note that we must adjust the forward - // references of the deleted entries to ensure iterators stuck - // in the middle of the list don't continue with deleted entries, - // but can continue with new entries added after the clear() - // operation. - var firstEntry = this.firstEntry; - var currentEntry = firstEntry.nextEntry; - while (currentEntry) { - var nextEntry = currentEntry.nextEntry; - currentEntry.previousEntry = undefined; - currentEntry.nextEntry = firstEntry; - currentEntry.skipNext = true; - currentEntry = nextEntry; - } - firstEntry.nextEntry = undefined; - this.lastEntry = firstEntry; - }; - class_1.prototype.keys = function () { - return new MapIterator(this.firstEntry, function (key) { return key; }); - }; - class_1.prototype.values = function () { - return new MapIterator(this.firstEntry, function (_key, value) { return value; }); - }; - class_1.prototype.entries = function () { - return new MapIterator(this.firstEntry, function (key, value) { return [key, value]; }); - }; - class_1.prototype.forEach = function (action) { - var iterator = this.entries(); - while (true) { - var iterResult = iterator.next(); - if (iterResult.done) { - break; - } - var _a = iterResult.value, key = _a[0], value = _a[1]; - action(value, key); - } - }; - return class_1; - }()); - } - ts.shimMap = shimMap; function length(array) { return array ? array.length : 0; } @@ -1855,20 +1725,6 @@ var ts; return str.indexOf(substring) !== -1; } ts.stringContains = stringContains; - function fileExtensionIs(path, extension) { - return path.length > extension.length && endsWith(path, extension); - } - ts.fileExtensionIs = fileExtensionIs; - function fileExtensionIsOneOf(path, extensions) { - for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { - var extension = extensions_1[_i]; - if (fileExtensionIs(path, extension)) { - return true; - } - } - return false; - } - ts.fileExtensionIsOneOf = fileExtensionIsOneOf; /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ @@ -2269,6 +2125,33 @@ var ts; ? function (node, message) { return assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, Debug.assertMissingNode); } : ts.noop; var isDebugInfoEnabled = false; + var extendedDebugModule; + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + function printControlFlowGraph(flowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + Debug.printControlFlowGraph = printControlFlowGraph; + function formatControlFlowGraph(flowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + Debug.formatControlFlowGraph = formatControlFlowGraph; + function attachFlowNodeDebugInfo(flowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value: function () { return formatControlFlowGraph(this); } } + }); + } + } + } + Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo; /** * Injects debug information into frequently used types. */ @@ -2312,6 +2195,20 @@ var ts; }); } } + // attempt to load extended debugging information + try { + if (ts.sys && ts.sys.require) { + var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath())); + var result = ts.sys.require(basePath, "./compiler-debug"); + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch (_a) { + // do nothing + } isDebugInfoEnabled = true; } Debug.enableDebugInfo = enableDebugInfo; @@ -2475,8 +2372,6 @@ var ts; } /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - var args = typeof process === "undefined" ? [] : process.argv; - ts.perfLogger.logInfoEvent("Starting TypeScript v" + ts.versionMajorMinor + " with command line: " + JSON.stringify(args)); })(ts || (ts = {})); /* @internal */ var ts; @@ -3371,6 +3266,7 @@ var ts; /* @internal */ TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags"; })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {})); + // NOTE: Ensure this is up-to-date with src/debug/debug.ts var FlowFlags; (function (FlowFlags) { FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable"; @@ -3426,6 +3322,8 @@ var ts; // When build skipped because passed in project is invalid ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped"; // When build is skipped because project references form cycle + ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped"; + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped"; })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {})); /* @internal */ @@ -3435,6 +3333,14 @@ var ts; UnionReduction[UnionReduction["Literal"] = 1] = "Literal"; UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype"; })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {})); + /* @internal */ + var ContextFlags; + (function (ContextFlags) { + ContextFlags[ContextFlags["None"] = 0] = "None"; + ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; + ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; + ContextFlags[ContextFlags["Completion"] = 4] = "Completion"; + })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {})); // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! var NodeBuilderFlags; (function (NodeBuilderFlags) { @@ -3876,6 +3782,18 @@ var ts; SignatureKind[SignatureKind["Call"] = 0] = "Call"; SignatureKind[SignatureKind["Construct"] = 1] = "Construct"; })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {})); + /* @internal */ + var SignatureFlags; + (function (SignatureFlags) { + SignatureFlags[SignatureFlags["None"] = 0] = "None"; + SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter"; + SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes"; + SignatureFlags[SignatureFlags["IsOptionalCall"] = 4] = "IsOptionalCall"; + // We do not propagate `IsOptionalCall` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + SignatureFlags[SignatureFlags["PropagatingFlags"] = 3] = "PropagatingFlags"; + })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {})); var IndexKind; (function (IndexKind) { IndexKind[IndexKind["String"] = 0] = "String"; @@ -5047,6 +4965,15 @@ var ts; bufferFrom: bufferFrom, base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); }, base64encode: function (input) { return bufferFrom(input).toString("base64"); }, + require: function (baseDir, moduleName) { + try { + var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath: modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error: error }; + } + } }; return nodeSystem; /** @@ -5185,6 +5112,7 @@ var ts; if (fsSupportsRecursive) { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. var watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? @@ -5629,6 +5557,673 @@ var ts; ts.Debug.isDebugging = true; } })(ts || (ts = {})); +/* @internal */ +var ts; +(function (ts) { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + ts.directorySeparator = "/"; + var altDirectorySeparator = "\\"; + var urlSchemeSeparator = "://"; + var backslashRegExp = /\\/g; + //// Path Tests + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + function isAnyDirectorySeparator(charCode) { + return charCode === 47 /* slash */ || charCode === 92 /* backslash */; + } + ts.isAnyDirectorySeparator = isAnyDirectorySeparator; + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + function isUrl(path) { + return getEncodedRootLength(path) < 0; + } + ts.isUrl = isUrl; + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + function isRootedDiskPath(path) { + return getEncodedRootLength(path) > 0; + } + ts.isRootedDiskPath = isRootedDiskPath; + /** + * Determines whether a path consists only of a path root. + */ + function isDiskPathRoot(path) { + var rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + ts.isDiskPathRoot = isDiskPathRoot; + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + function pathIsAbsolute(path) { + return getEncodedRootLength(path) !== 0; + } + ts.pathIsAbsolute = pathIsAbsolute; + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + function pathIsRelative(path) { + return /^\.\.?($|[\\/])/.test(path); + } + ts.pathIsRelative = pathIsRelative; + function hasExtension(fileName) { + return ts.stringContains(getBaseFileName(fileName), "."); + } + ts.hasExtension = hasExtension; + function fileExtensionIs(path, extension) { + return path.length > extension.length && ts.endsWith(path, extension); + } + ts.fileExtensionIs = fileExtensionIs; + function fileExtensionIsOneOf(path, extensions) { + for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) { + var extension = extensions_1[_i]; + if (fileExtensionIs(path, extension)) { + return true; + } + } + return false; + } + ts.fileExtensionIsOneOf = fileExtensionIsOneOf; + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + function hasTrailingDirectorySeparator(path) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; + //// Path Parsing + function isVolumeCharacter(charCode) { + return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || + (charCode >= 65 /* A */ && charCode <= 90 /* Z */); + } + function getFileUrlVolumeSeparatorEnd(url, start) { + var ch0 = url.charCodeAt(start); + if (ch0 === 58 /* colon */) + return start + 1; + if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { + var ch2 = url.charCodeAt(start + 2); + if (ch2 === 97 /* a */ || ch2 === 65 /* A */) + return start + 3; + } + return -1; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path) { + if (!path) + return 0; + var ch0 = path.charCodeAt(0); + // POSIX or UNC + if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { + if (path.charCodeAt(1) !== ch0) + return 1; // POSIX: "/" (or non-normalized "\") + var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) + return path.length; // UNC: "//server" or "\\server" + return p1 + 1; // UNC: "//server/" or "\\server\" + } + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { + var ch2 = path.charCodeAt(2); + if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) + return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) + return 2; // DOS: "c:" (but not "c:d") + } + // URL + var schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + var authorityStart = schemeEnd + urlSchemeSeparator.length; + var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + var scheme = path.slice(0, schemeEnd); + var authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + // relative + return 0; + } + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + function getRootLength(path) { + var rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + ts.getRootLength = getRootLength; + function getDirectoryPath(path) { + path = normalizeSlashes(path); + // If the path provided is itself the root, then return it. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return path; + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); + } + ts.getDirectoryPath = getDirectoryPath; + function getBaseFileName(path, extensions, ignoreCase) { + path = normalizeSlashes(path); + // if the path provided is itself the root, then it has not file name. + var rootLength = getRootLength(path); + if (rootLength === path.length) + return ""; + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); + var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + ts.getBaseFileName = getBaseFileName; + function tryGetExtensionFromPath(path, extension, stringEqualityComparer) { + if (!ts.startsWith(extension, ".")) + extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) { + var pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { + var extension = extensions_2[_i]; + var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) + return result; + } + return ""; + } + function getAnyExtensionFromPath(path, extensions, ignoreCase) { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); + } + var baseFileName = getBaseFileName(path); + var extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + ts.getAnyExtensionFromPath = getAnyExtensionFromPath; + function pathComponents(path, rootLength) { + var root = path.substring(0, rootLength); + var rest = path.substring(rootLength).split(ts.directorySeparator); + if (rest.length && !ts.lastOrUndefined(rest)) + rest.pop(); + return __spreadArrays([root], rest); + } + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + function getPathComponents(path, currentDirectory) { + if (currentDirectory === void 0) { currentDirectory = ""; } + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + ts.getPathComponents = getPathComponents; + //// Path Formatting + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + function getPathFromPathComponents(pathComponents) { + if (pathComponents.length === 0) + return ""; + var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(ts.directorySeparator); + } + ts.getPathFromPathComponents = getPathFromPathComponents; + //// Path Normalization + /** + * Normalize path separators, converting `\` into `/`. + */ + function normalizeSlashes(path) { + return path.replace(backslashRegExp, ts.directorySeparator); + } + ts.normalizeSlashes = normalizeSlashes; + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + function reducePathComponents(components) { + if (!ts.some(components)) + return []; + var reduced = [components[0]]; + for (var i = 1; i < components.length; i++) { + var component = components[i]; + if (!component) + continue; + if (component === ".") + continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) + continue; + } + reduced.push(component); + } + return reduced; + } + ts.reducePathComponents = reducePathComponents; + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + function combinePaths(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + if (path) + path = normalizeSlashes(path); + for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { + var relativePath = paths_1[_a]; + if (!relativePath) + continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + ts.combinePaths = combinePaths; + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + function resolvePath(path) { + var paths = []; + for (var _i = 1; _i < arguments.length; _i++) { + paths[_i - 1] = arguments[_i]; + } + return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path)); + } + ts.resolvePath = resolvePath; + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + function getNormalizedPathComponents(path, currentDirectory) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + ts.getNormalizedPathComponents = getNormalizedPathComponents; + function getNormalizedAbsolutePath(fileName, currentDirectory) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; + function normalizePath(path) { + path = normalizeSlashes(path); + var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + ts.normalizePath = normalizePath; + function getPathWithoutRoot(pathComponents) { + if (pathComponents.length === 0) + return ""; + return pathComponents.slice(1).join(ts.directorySeparator); + } + function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; + function toPath(fileName, basePath, getCanonicalFileName) { + var nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + ts.toPath = toPath; + function normalizePathAndParts(path) { + path = normalizeSlashes(path); + var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); + if (parts.length) { + var joinedParts = root + parts.join(ts.directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; + } + else { + return { path: root, parts: parts }; + } + } + ts.normalizePathAndParts = normalizePathAndParts; + function removeTrailingDirectorySeparator(path) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + return path; + } + ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; + function ensureTrailingDirectorySeparator(path) { + if (!hasTrailingDirectorySeparator(path)) { + return path + ts.directorySeparator; + } + return path; + } + ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + function ensurePathIsNonModuleName(path) { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; + function changeAnyExtension(path, ext, extensions, ignoreCase) { + var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; + } + ts.changeAnyExtension = changeAnyExtension; + //// Path Comparisons + // check path for these segments: '', '.'. '..' + var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + function comparePathsWorker(a, b, componentComparer) { + if (a === b) + return 0 /* EqualTo */; + if (a === undefined) + return -1 /* LessThan */; + if (b === undefined) + return 1 /* GreaterThan */; + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + var aRoot = a.substring(0, getRootLength(a)); + var bRoot = b.substring(0, getRootLength(b)); + var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== 0 /* EqualTo */) { + return result; + } + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + var aRest = a.substring(aRoot.length); + var bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + var aComponents = reducePathComponents(getPathComponents(a)); + var bComponents = reducePathComponents(getPathComponents(b)); + var sharedLength = Math.min(aComponents.length, bComponents.length); + for (var i = 1; i < sharedLength; i++) { + var result_1 = componentComparer(aComponents[i], bComponents[i]); + if (result_1 !== 0 /* EqualTo */) { + return result_1; + } + } + return ts.compareValues(aComponents.length, bComponents.length); + } + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + function comparePathsCaseSensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); + } + ts.comparePathsCaseSensitive = comparePathsCaseSensitive; + /** + * Performs a case-insensitive comparison of two paths. + */ + function comparePathsCaseInsensitive(a, b) { + return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); + } + ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; + function comparePaths(a, b, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); + } + ts.comparePaths = comparePaths; + function containsPath(parent, child, currentDirectory, ignoreCase) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) + return false; + if (parent === child) + return true; + var parentComponents = reducePathComponents(getPathComponents(parent)); + var childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; + for (var i = 0; i < parentComponents.length; i++) { + var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + return true; + } + ts.containsPath = containsPath; + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { + var canonicalFileName = getCanonicalFileName(fileName); + var canonicalDirectoryName = getCanonicalFileName(directoryName); + return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + ts.startsWithDirectory = startsWithDirectory; + //// Relative Paths + function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { + var fromComponents = reducePathComponents(getPathComponents(from)); + var toComponents = reducePathComponents(getPathComponents(to)); + var start; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + var fromComponent = getCanonicalFileName(fromComponents[start]); + var toComponent = getCanonicalFileName(toComponents[start]); + var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) + break; + } + if (start === 0) { + return toComponents; + } + var components = toComponents.slice(start); + var relative = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return __spreadArrays([""], relative, components); + } + ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; + function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { + ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; + var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathFromDirectory = getRelativePathFromDirectory; + function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + ts.convertToRelativePath = convertToRelativePath; + function getRelativePathFromFile(from, to, getCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + ts.getRelativePathFromFile = getRelativePathFromFile; + function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { + var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); + var firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + return getPathFromPathComponents(pathComponents); + } + ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; + function forEachAncestorDirectory(directory, callback) { + while (true) { + var result = callback(directory); + if (result !== undefined) { + return result; + } + var parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + directory = parentPath; + } + } + ts.forEachAncestorDirectory = forEachAncestorDirectory; +})(ts || (ts = {})); // // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler' /* @internal */ @@ -5656,7 +6251,7 @@ var ts; An_index_signature_parameter_cannot_have_an_initializer: diag(1020, ts.DiagnosticCategory.Error, "An_index_signature_parameter_cannot_have_an_initializer_1020", "An index signature parameter cannot have an initializer."), An_index_signature_must_have_a_type_annotation: diag(1021, ts.DiagnosticCategory.Error, "An_index_signature_must_have_a_type_annotation_1021", "An index signature must have a type annotation."), An_index_signature_parameter_must_have_a_type_annotation: diag(1022, ts.DiagnosticCategory.Error, "An_index_signature_parameter_must_have_a_type_annotation_1022", "An index signature parameter must have a type annotation."), - An_index_signature_parameter_type_must_be_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_string_or_number_1023", "An index signature parameter type must be 'string' or 'number'."), + An_index_signature_parameter_type_must_be_either_string_or_number: diag(1023, ts.DiagnosticCategory.Error, "An_index_signature_parameter_type_must_be_either_string_or_number_1023", "An index signature parameter type must be either 'string' or 'number'."), readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature: diag(1024, ts.DiagnosticCategory.Error, "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024", "'readonly' modifier can only appear on a property declaration or index signature."), Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."), _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."), @@ -5864,7 +6459,7 @@ var ts; Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1320, ts.DiagnosticCategory.Error, "Type_of_await_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member_1320", "Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member."), Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1321, ts.DiagnosticCategory.Error, "Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_cal_1321", "Type of 'yield' operand in an async generator must either be a valid promise or must not contain a callable 'then' member."), Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member: diag(1322, ts.DiagnosticCategory.Error, "Type_of_iterated_elements_of_a_yield_Asterisk_operand_must_either_be_a_valid_promise_or_must_not_con_1322", "Type of iterated elements of a 'yield*' operand must either be a valid promise or must not contain a callable 'then' member."), - Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext_1323", "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'."), + Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd: diag(1323, ts.DiagnosticCategory.Error, "Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd_1323", "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'."), Dynamic_import_must_have_one_specifier_as_an_argument: diag(1324, ts.DiagnosticCategory.Error, "Dynamic_import_must_have_one_specifier_as_an_argument_1324", "Dynamic import must have one specifier as an argument."), Specifier_of_dynamic_import_cannot_be_spread_element: diag(1325, ts.DiagnosticCategory.Error, "Specifier_of_dynamic_import_cannot_be_spread_element_1325", "Specifier of dynamic import cannot be spread element."), Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments"), @@ -5899,6 +6494,7 @@ var ts; Did_you_mean_to_mark_this_function_as_async: diag(1356, ts.DiagnosticCategory.Error, "Did_you_mean_to_mark_this_function_as_async_1356", "Did you mean to mark this function as 'async'?"), An_enum_member_name_must_be_followed_by_a_or: diag(1357, ts.DiagnosticCategory.Error, "An_enum_member_name_must_be_followed_by_a_or_1357", "An enum member name must be followed by a ',', '=', or '}'."), Tagged_template_expressions_are_not_permitted_in_an_optional_chain: diag(1358, ts.DiagnosticCategory.Error, "Tagged_template_expressions_are_not_permitted_in_an_optional_chain_1358", "Tagged template expressions are not permitted in an optional chain."), + Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here: diag(1359, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here_1359", "Identifier expected. '{0}' is a reserved word that cannot be used here."), The_types_of_0_are_incompatible_between_these_types: diag(2200, ts.DiagnosticCategory.Error, "The_types_of_0_are_incompatible_between_these_types_2200", "The types of '{0}' are incompatible between these types."), The_types_returned_by_0_are_incompatible_between_these_types: diag(2201, ts.DiagnosticCategory.Error, "The_types_returned_by_0_are_incompatible_between_these_types_2201", "The types returned by '{0}' are incompatible between these types."), Call_signature_return_types_0_and_1_are_incompatible: diag(2202, ts.DiagnosticCategory.Error, "Call_signature_return_types_0_and_1_are_incompatible_2202", "Call signature return types '{0}' and '{1}' are incompatible.", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ true), @@ -6026,7 +6622,6 @@ var ts; Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."), A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members: diag(2422, ts.DiagnosticCategory.Error, "A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_memb_2422", "A class can only implement an object type or intersection of object types with statically known members."), Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2423, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_access_2423", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member accessor."), - Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2424, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_proper_2424", "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2425, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_functi_2425", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function."), Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function: diag(2426, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_functi_2426", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member function."), Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."), @@ -6199,6 +6794,8 @@ var ts; Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_property: diag(2610, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_proper_2610", "Class '{0}' defines instance member accessor '{1}', but extended class '{2}' defines it as instance member property."), Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_accessor: diag(2611, ts.DiagnosticCategory.Error, "Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_access_2611", "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member accessor."), Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_add_a_declare_modifier_or_remove_the_redundant_declaration: diag(2612, ts.DiagnosticCategory.Error, "Property_0_will_overwrite_the_base_property_in_1_If_this_is_intentional_add_an_initializer_Otherwise_2612", "Property '{0}' will overwrite the base property in '{1}'. If this is intentional, add an initializer. Otherwise, add a 'declare' modifier or remove the redundant declaration."), + Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead: diag(2613, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead_2613", "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?"), + Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead: diag(2614, ts.DiagnosticCategory.Error, "Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead_2614", "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?"), Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity: diag(2649, ts.DiagnosticCategory.Error, "Cannot_augment_module_0_with_value_exports_because_it_resolves_to_a_non_module_entity_2649", "Cannot augment module '{0}' with value exports because it resolves to a non-module entity."), A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums: diag(2651, ts.DiagnosticCategory.Error, "A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_memb_2651", "A member initializer in a enum declaration cannot reference members declared after it, including members defined in other enums."), Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_default_0_declaration_instead: diag(2652, ts.DiagnosticCategory.Error, "Merged_declaration_0_cannot_include_a_default_export_declaration_Consider_adding_a_separate_export_d_2652", "Merged declaration '{0}' cannot include a default export declaration. Consider adding a separate 'export default {0}' declaration instead."), @@ -6709,6 +7306,7 @@ var ts; The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1: diag(6500, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_property_0_which_is_declared_here_on_type_1_6500", "The expected type comes from property '{0}' which is declared here on type '{1}'"), The_expected_type_comes_from_this_index_signature: diag(6501, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_this_index_signature_6501", "The expected type comes from this index signature."), The_expected_type_comes_from_the_return_type_of_this_signature: diag(6502, ts.DiagnosticCategory.Message, "The_expected_type_comes_from_the_return_type_of_this_signature_6502", "The expected type comes from the return type of this signature."), + Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing: diag(6503, ts.DiagnosticCategory.Message, "Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing_6503", "Print names of files that are part of the compilation and then stop processing."), 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."), @@ -9044,7 +9642,7 @@ var ts; ts.getDeclarationOfKind = getDeclarationOfKind; /** Create a new escaped identifier map. */ function createUnderscoreEscapedMap() { - return new ts.MapCtr(); + return new ts.Map(); } ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap; function hasEntries(map) { @@ -9100,13 +9698,6 @@ var ts; reportPrivateInBaseOfClassExpression: ts.noop, }; } - function toPath(fileName, basePath, getCanonicalFileName) { - var nonCanonicalizedPath = ts.isRootedDiskPath(fileName) - ? ts.normalizePath(fileName) - : ts.getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - ts.toPath = toPath; function changesAffectModuleResolution(oldOptions, newOptions) { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -9913,6 +10504,11 @@ var ts; break; case 201 /* ArrowFunction */: return getErrorSpanForArrowFunction(sourceFile, node); + case 275 /* CaseClause */: + case 276 /* DefaultClause */: + var start = ts.skipTrivia(sourceFile.text, node.pos); + var end = node.statements.length > 0 ? node.statements[0].pos : node.end; + return ts.createTextSpanFromBounds(start, end); } if (errorNode === undefined) { // If we don't have a better node, then just set the error on the first token of @@ -10725,7 +11321,7 @@ var ts; (node.typeArguments[0].kind === 142 /* StringKeyword */ || node.typeArguments[0].kind === 139 /* NumberKeyword */); } ts.isJSDocIndexSignature = isJSDocIndexSignature; - function isRequireCall(callExpression, checkArgumentIsStringLiteralLike) { + function isRequireCall(callExpression, requireStringLiteralLikeArgument) { if (callExpression.kind !== 195 /* CallExpression */) { return false; } @@ -10737,7 +11333,7 @@ var ts; return false; } var arg = args[0]; - return !checkArgumentIsStringLiteralLike || ts.isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg); } ts.isRequireCall = isRequireCall; function isSingleOrDoubleQuote(charCode) { @@ -10956,7 +11552,7 @@ var ts; ts.idText(expr.expression.expression) === "Object" && ts.idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && - isBindableStaticNameExpression(expr.arguments[0]); + isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall; function isBindableStaticElementAccessExpression(node, excludeThisKeyword) { @@ -11064,9 +11660,11 @@ var ts; nextToLast = nextToLast.expression; } var id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return 1 /* ExportsProperty */; } // F.G...x = expr @@ -12392,7 +12990,7 @@ var ts; */ function getExternalModuleNameFromPath(host, fileName, referencePath) { var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); }; - var dir = toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); + var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName); var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory()); var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); var extensionless = ts.removeFileExtension(relativePath); @@ -12914,6 +13512,23 @@ var ts; return node.kind === 75 /* Identifier */ || isPropertyAccessEntityNameExpression(node); } ts.isEntityNameExpression = isEntityNameExpression; + function getFirstIdentifier(node) { + switch (node.kind) { + case 75 /* Identifier */: + return node; + case 152 /* QualifiedName */: + do { + node = node.left; + } while (node.kind !== 75 /* Identifier */); + return node; + case 193 /* PropertyAccessExpression */: + do { + node = node.expression; + } while (node.kind !== 75 /* Identifier */); + return node; + } + } + ts.getFirstIdentifier = getFirstIdentifier; function isDottedName(node) { return node.kind === 75 /* Identifier */ || node.kind === 103 /* ThisKeyword */ || node.kind === 193 /* PropertyAccessExpression */ && isDottedName(node.expression) || @@ -13432,20 +14047,6 @@ var ts; }); } ts.mutateMap = mutateMap; - function forEachAncestorDirectory(directory, callback) { - while (true) { - var result = callback(directory); - if (result !== undefined) { - return result; - } - var parentPath = ts.getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - directory = parentPath; - } - } - ts.forEachAncestorDirectory = forEachAncestorDirectory; // Return true if the given type is the constructor type for an abstract class function isAbstractConstructorType(type) { return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -13472,7 +14073,7 @@ var ts; } ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures; function forSomeAncestorDirectory(directory, callback) { - return !!forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); + return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; }); } ts.forSomeAncestorDirectory = forSomeAncestorDirectory; function isUMDExportSymbol(symbol) { @@ -14537,11 +15138,21 @@ var ts; } ts.isCallChain = isCallChain; function isOptionalChain(node) { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + var kind = node.kind; + return !!(node.flags & 32 /* OptionalChain */) && + (kind === 193 /* PropertyAccessExpression */ + || kind === 194 /* ElementAccessExpression */ + || kind === 195 /* CallExpression */); } ts.isOptionalChain = isOptionalChain; + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + function isExpressionOfOptionalChainRoot(node) { + return ts.isOptionalChainRoot(node.parent) && node.parent.expression === node; + } + ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot; function isNewExpression(node) { return node.kind === 196 /* NewExpression */; } @@ -15903,7 +16514,12 @@ var ts; this.checker = checker; } } - function Signature() { } + function Signature(checker, flags) { + this.flags = flags; + if (ts.Debug.isDebugging) { + this.checker = checker; + } + } function Node(kind, pos, end) { this.pos = pos; this.end = end; @@ -16178,273 +16794,6 @@ var ts; return true; } ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter; - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - ts.directorySeparator = "/"; - var altDirectorySeparator = "\\"; - var urlSchemeSeparator = "://"; - var backslashRegExp = /\\/g; - /** - * Normalize path separators. - */ - function normalizeSlashes(path) { - return path.replace(backslashRegExp, ts.directorySeparator); - } - ts.normalizeSlashes = normalizeSlashes; - function isVolumeCharacter(charCode) { - return (charCode >= 97 /* a */ && charCode <= 122 /* z */) || - (charCode >= 65 /* A */ && charCode <= 90 /* Z */); - } - function getFileUrlVolumeSeparatorEnd(url, start) { - var ch0 = url.charCodeAt(start); - if (ch0 === 58 /* colon */) - return start + 1; - if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) { - var ch2 = url.charCodeAt(start + 2); - if (ch2 === 97 /* a */ || ch2 === 65 /* A */) - return start + 3; - } - return -1; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path) { - if (!path) - return 0; - var ch0 = path.charCodeAt(0); - // POSIX or UNC - if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) { - if (path.charCodeAt(1) !== ch0) - return 1; // POSIX: "/" (or non-normalized "\") - var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) - return path.length; // UNC: "//server" or "\\server" - return p1 + 1; // UNC: "//server/" or "\\server\" - } - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) { - var ch2 = path.charCodeAt(2); - if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */) - return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) - return 2; // DOS: "c:" (but not "c:d") - } - // URL - var schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - var authorityStart = schemeEnd + urlSchemeSeparator.length; - var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - var scheme = path.slice(0, schemeEnd); - var authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - // relative - return 0; - } - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - function getRootLength(path) { - var rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - ts.getRootLength = getRootLength; - // TODO(rbuckton): replace references with `resolvePath` - function normalizePath(path) { - return ts.resolvePath(path); - } - ts.normalizePath = normalizePath; - function normalizePathAndParts(path) { - path = normalizeSlashes(path); - var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1); - if (parts.length) { - var joinedParts = root + parts.join(ts.directorySeparator); - return { path: ts.hasTrailingDirectorySeparator(path) ? ts.ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts }; - } - else { - return { path: root, parts: parts }; - } - } - ts.normalizePathAndParts = normalizePathAndParts; - function getDirectoryPath(path) { - path = normalizeSlashes(path); - // If the path provided is itself the root, then return it. - var rootLength = getRootLength(path); - if (rootLength === path.length) - return path; - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = ts.removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator))); - } - ts.getDirectoryPath = getDirectoryPath; - function startsWithDirectory(fileName, directoryName, getCanonicalFileName) { - var canonicalFileName = getCanonicalFileName(fileName); - var canonicalDirectoryName = getCanonicalFileName(directoryName); - return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - ts.startsWithDirectory = startsWithDirectory; - function isUrl(path) { - return getEncodedRootLength(path) < 0; - } - ts.isUrl = isUrl; - function pathIsRelative(path) { - return /^\.\.?($|[\\/])/.test(path); - } - ts.pathIsRelative = pathIsRelative; - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - function isRootedDiskPath(path) { - return getEncodedRootLength(path) > 0; - } - ts.isRootedDiskPath = isRootedDiskPath; - /** - * Determines whether a path consists only of a path root. - */ - function isDiskPathRoot(path) { - var rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - ts.isDiskPathRoot = isDiskPathRoot; - function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : ts.getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - ts.convertToRelativePath = convertToRelativePath; - function pathComponents(path, rootLength) { - var root = path.substring(0, rootLength); - var rest = path.substring(rootLength).split(ts.directorySeparator); - if (rest.length && !ts.lastOrUndefined(rest)) - rest.pop(); - return __spreadArrays([root], rest); - } - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getPathComponents(path, currentDirectory) { - if (currentDirectory === void 0) { currentDirectory = ""; } - path = ts.combinePaths(currentDirectory, path); - var rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - ts.getPathComponents = getPathComponents; - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - function reducePathComponents(components) { - if (!ts.some(components)) - return []; - var reduced = [components[0]]; - for (var i = 1; i < components.length; i++) { - var component = components[i]; - if (!component) - continue; - if (component === ".") - continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) - continue; - } - reduced.push(component); - } - return reduced; - } - ts.reducePathComponents = reducePathComponents; - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - function getNormalizedPathComponents(path, currentDirectory) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - ts.getNormalizedPathComponents = getNormalizedPathComponents; - function getNormalizedAbsolutePath(fileName, currentDirectory) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath; - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - function getPathFromPathComponents(pathComponents) { - if (pathComponents.length === 0) - return ""; - var root = pathComponents[0] && ts.ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(ts.directorySeparator); - } - ts.getPathFromPathComponents = getPathFromPathComponents; - function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot; - function getPathWithoutRoot(pathComponents) { - if (pathComponents.length === 0) - return ""; - return pathComponents.slice(1).join(ts.directorySeparator); - } function discoverProbableSymlinks(files, getCanonicalFileName, cwd) { var result = ts.createMap(); var symlinks = ts.flatten(ts.mapDefined(files, function (sf) { @@ -16461,15 +16810,15 @@ var ts; } ts.discoverProbableSymlinks = discoverProbableSymlinks; function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) { - var aParts = getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); - var bParts = getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); + var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName)); + var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName)); while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) && !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) && getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) { aParts.pop(); bParts.pop(); } - return [getPathFromPathComponents(aParts), getPathFromPathComponents(bParts)]; + return [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)]; } // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink. // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked. @@ -16479,229 +16828,8 @@ var ts; })(ts || (ts = {})); /* @internal */ (function (ts) { - function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) { - var fromComponents = ts.reducePathComponents(ts.getPathComponents(from)); - var toComponents = ts.reducePathComponents(ts.getPathComponents(to)); - var start; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - var fromComponent = getCanonicalFileName(fromComponents[start]); - var toComponent = getCanonicalFileName(toComponents[start]); - var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) - break; - } - if (start === 0) { - return toComponents; - } - var components = toComponents.slice(start); - var relative = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return __spreadArrays([""], relative, components); - } - ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo; - function getRelativePathFromFile(from, to, getCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(ts.getDirectoryPath(from), to, getCanonicalFileName)); - } - ts.getRelativePathFromFile = getRelativePathFromFile; - function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) { - ts.Debug.assert((ts.getRootLength(fromDirectory) > 0) === (ts.getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity; - var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName); - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathFromDirectory = getRelativePathFromDirectory; - function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) { - var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName); - var firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && ts.isRootedDiskPath(firstComponent)) { - var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - return ts.getPathFromPathComponents(pathComponents); - } - ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl; - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - function ensurePathIsNonModuleName(path) { - return ts.getRootLength(path) === 0 && !ts.pathIsRelative(path) ? "./" + path : path; - } - ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName; - function getBaseFileName(path, extensions, ignoreCase) { - path = ts.normalizeSlashes(path); - // if the path provided is itself the root, then it has not file name. - var rootLength = ts.getRootLength(path); - if (rootLength === path.length) - return ""; - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - var name = path.slice(Math.max(ts.getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1)); - var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - ts.getBaseFileName = getBaseFileName; - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - function combinePaths(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - if (path) - path = ts.normalizeSlashes(path); - for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) { - var relativePath = paths_1[_a]; - if (!relativePath) - continue; - relativePath = ts.normalizeSlashes(relativePath); - if (!path || ts.getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - ts.combinePaths = combinePaths; - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - function resolvePath(path) { - var paths = []; - for (var _i = 1; _i < arguments.length; _i++) { - paths[_i - 1] = arguments[_i]; - } - var combined = ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : ts.normalizeSlashes(path); - var normalized = ts.getPathFromPathComponents(ts.reducePathComponents(ts.getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - ts.resolvePath = resolvePath; - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - function hasTrailingDirectorySeparator(path) { - if (path.length === 0) - return false; - var ch = path.charCodeAt(path.length - 1); - return ch === 47 /* slash */ || ch === 92 /* backslash */; - } - ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator; - function removeTrailingDirectorySeparator(path) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - return path; - } - ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator; - function ensureTrailingDirectorySeparator(path) { - if (!hasTrailingDirectorySeparator(path)) { - return path + ts.directorySeparator; - } - return path; - } - ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator; - // check path for these segments: '', '.'. '..' - var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - function comparePathsWorker(a, b, componentComparer) { - if (a === b) - return 0 /* EqualTo */; - if (a === undefined) - return -1 /* LessThan */; - if (b === undefined) - return 1 /* GreaterThan */; - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - var aRoot = a.substring(0, ts.getRootLength(a)); - var bRoot = b.substring(0, ts.getRootLength(b)); - var result = ts.compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== 0 /* EqualTo */) { - return result; - } - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - var aRest = a.substring(aRoot.length); - var bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - var aComponents = ts.reducePathComponents(ts.getPathComponents(a)); - var bComponents = ts.reducePathComponents(ts.getPathComponents(b)); - var sharedLength = Math.min(aComponents.length, bComponents.length); - for (var i = 1; i < sharedLength; i++) { - var result_1 = componentComparer(aComponents[i], bComponents[i]); - if (result_1 !== 0 /* EqualTo */) { - return result_1; - } - } - return ts.compareValues(aComponents.length, bComponents.length); - } - /** - * Performs a case-sensitive comparison of two paths. - */ - function comparePathsCaseSensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseSensitive); - } - ts.comparePathsCaseSensitive = comparePathsCaseSensitive; - /** - * Performs a case-insensitive comparison of two paths. - */ - function comparePathsCaseInsensitive(a, b) { - return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive); - } - ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive; - function comparePaths(a, b, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase)); - } - ts.comparePaths = comparePaths; - function containsPath(parent, child, currentDirectory, ignoreCase) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) - return false; - if (parent === child) - return true; - var parentComponents = ts.reducePathComponents(ts.getPathComponents(parent)); - var childComponents = ts.reducePathComponents(ts.getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive; - for (var i = 0; i < parentComponents.length; i++) { - var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - return true; - } - ts.containsPath = containsPath; - function isDirectorySeparator(charCode) { - return charCode === 47 /* slash */ || charCode === 92 /* backslash */; - } function stripLeadingDirectorySeparator(s) { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) { var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName); @@ -16720,10 +16848,6 @@ var ts; return "\\" + match; } var wildcardCharCodes = [42 /* asterisk */, 63 /* question */]; - function hasExtension(fileName) { - return ts.stringContains(getBaseFileName(fileName), "."); - } - ts.hasExtension = hasExtension; ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"]; var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))"; var filesMatcher = { @@ -16799,7 +16923,7 @@ var ts; } // getNormalizedPathComponents includes the separator for the root component. // We need to remove to create our regex correctly. - components[0] = removeTrailingDirectorySeparator(components[0]); + components[0] = ts.removeTrailingDirectorySeparator(components[0]); if (isImplicitGlob(lastComponent)) { components.push("**", "*"); } @@ -16861,7 +16985,7 @@ var ts; function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) { path = ts.normalizePath(path); currentDirectory = ts.normalizePath(currentDirectory); - var absolutePath = combinePaths(currentDirectory, path); + var absolutePath = ts.combinePaths(currentDirectory, path); return { includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }), includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"), @@ -16890,7 +17014,7 @@ var ts; var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames); for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) { var basePath = _a[_i]; - visitDirectory(basePath, combinePaths(currentDirectory, basePath), depth); + visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth); } return ts.flatten(results); function visitDirectory(path, absolutePath, depth) { @@ -16900,8 +17024,8 @@ var ts; visited.set(canonicalPath, true); var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories; var _loop_1 = function (current) { - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if (extensions && !ts.fileExtensionIsOneOf(name, extensions)) return "continue"; if (excludeRegex && excludeRegex.test(absoluteName)) @@ -16928,8 +17052,8 @@ var ts; } for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) { var current = _d[_c]; - var name = combinePaths(path, current); - var absoluteName = combinePaths(absolutePath, current); + var name = ts.combinePaths(path, current); + var absoluteName = ts.combinePaths(absolutePath, current); if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) && (!excludeRegex || !excludeRegex.test(absoluteName))) { visitDirectory(name, absoluteName, depth); @@ -16951,14 +17075,14 @@ var ts; var include = includes_1[_i]; // We also need to check the relative paths by converting them to absolute and normalizing // in case they escape the base path (e.g "..\somedirectory") - var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(combinePaths(path, include)); + var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include)); // Append the literal and canonical candidate base paths. includeBasePaths.push(getIncludeBasePath(absolute)); } // Sort the offsets array using either the literal or canonical path representations. includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames)); var _loop_2 = function (includeBasePath) { - if (ts.every(basePaths, function (basePath) { return !containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { + if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) { basePaths.push(includeBasePath); } }; @@ -16975,9 +17099,9 @@ var ts; var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes); if (wildcardOffset < 0) { // No "*" or "?" in the path - return !hasExtension(absolute) + return !ts.hasExtension(absolute) ? absolute - : removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); + : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute)); } return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset)); } @@ -17142,14 +17266,9 @@ var ts; } ts.removeExtension = removeExtension; function changeExtension(path, newExtension) { - return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); + return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } ts.changeExtension = changeExtension; - function changeAnyExtension(path, ext, extensions, ignoreCase) { - var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path; - } - ts.changeAnyExtension = changeAnyExtension; function tryParsePattern(pattern) { // This should be verified outside of here and a proper error thrown. ts.Debug.assert(ts.hasZeroOrOneAsteriskCharacter(pattern)); @@ -17192,36 +17311,6 @@ var ts; return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); }); } ts.tryGetExtensionFromPath = tryGetExtensionFromPath; - function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) { - if (typeof extensions === "string") - extensions = [extensions]; - for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) { - var extension = extensions_2[_i]; - if (!ts.startsWith(extension, ".")) - extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - var pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - function getAnyExtensionFromPath(path, extensions, ignoreCase) { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive); - } - var baseFileName = getBaseFileName(path); - var extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - ts.getAnyExtensionFromPath = getAnyExtensionFromPath; function isCheckJsEnabledForFile(sourceFile, compilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } @@ -18732,7 +18821,12 @@ var ts; } // Only for end of file because the error gets reported incorrectly on embedded script tags. var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */; - return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || ts.Diagnostics.Identifier_expected); + var isReservedWord = scanner.isReservedWord(); + var msgArg = scanner.getTokenText(); + var defaultMessage = isReservedWord ? + ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : + ts.Diagnostics.Identifier_expected; + return createMissingNode(75 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); } function parseIdentifier(diagnosticMessage) { return createIdentifier(isIdentifier(), diagnosticMessage); @@ -25059,6 +25153,15 @@ var ts; isCommandLineOnly: true, description: ts.Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: ts.Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { name: "target", @@ -26051,6 +26154,7 @@ var ts; return { buildOptions: buildOptions, projects: projects, errors: errors }; } ts.parseBuildCommand = parseBuildCommand; + /* @internal */ function getDiagnosticText(_message) { var _args = []; for (var _i = 1; _i < arguments.length; _i++) { @@ -26059,104 +26163,7 @@ var ts; var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - function printVersion() { - ts.sys.write(getDiagnosticText(ts.Diagnostics.Version_0, ts.version) + ts.sys.newLine); - } - ts.printVersion = printVersion; - /* @internal */ - function printHelp(optionsList, syntaxPrefix) { - if (syntaxPrefix === void 0) { syntaxPrefix = ""; } - var output = []; - // We want to align our "syntax" and "examples" commands to a certain margin. - var syntaxLength = getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, "").length; - var examplesLength = getDiagnosticText(ts.Diagnostics.Examples_Colon_0, "").length; - var marginLength = Math.max(syntaxLength, examplesLength); - // Build up the syntactic skeleton. - var syntax = makePadding(marginLength - syntaxLength); - syntax += "tsc " + syntaxPrefix + "[" + getDiagnosticText(ts.Diagnostics.options) + "] [" + getDiagnosticText(ts.Diagnostics.file) + "...]"; - output.push(getDiagnosticText(ts.Diagnostics.Syntax_Colon_0, syntax)); - output.push(ts.sys.newLine + ts.sys.newLine); - // Build up the list of examples. - var padding = makePadding(marginLength); - output.push(getDiagnosticText(ts.Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + ts.sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + ts.sys.newLine); - output.push(padding + "tsc @args.txt" + ts.sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + ts.sys.newLine); - output.push(ts.sys.newLine); - output.push(getDiagnosticText(ts.Diagnostics.Options_Colon) + ts.sys.newLine); - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - var usageColumn = []; // Things like "-d, --declaration" go in here. - var descriptionColumn = []; - var optionsDescriptionMap = ts.createMap(); // Map between option.description and list of option.type if it is a kind - for (var _i = 0, optionsList_1 = optionsList; _i < optionsList_1.length; _i++) { - var option = optionsList_1[_i]; - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - var usageText_1 = " "; - if (option.shortName) { - usageText_1 += "-" + option.shortName; - usageText_1 += getParamType(option); - usageText_1 += ", "; - } - usageText_1 += "--" + option.name; - usageText_1 += getParamType(option); - usageColumn.push(usageText_1); - var description = void 0; - if (option.name === "lib") { - description = getDiagnosticText(option.description); - var element = option.element; - var typeMap = element.type; - optionsDescriptionMap.set(description, ts.arrayFrom(typeMap.keys()).map(function (key) { return "'" + key + "'"; })); - } - else { - description = getDiagnosticText(option.description); - } - descriptionColumn.push(description); - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText_1.length, marginLength); - } - // Special case that can't fit in the loop. - var usageText = " @<" + getDiagnosticText(ts.Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(ts.Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - // Print out each row, aligning all the descriptions on the same column. - for (var i = 0; i < usageColumn.length; i++) { - var usage = usageColumn[i]; - var description = descriptionColumn[i]; - var kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + ts.sys.newLine); - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (var _a = 0, kindsList_1 = kindsList; _a < kindsList_1.length; _a++) { - var kind = kindsList_1[_a]; - output.push(kind + " "); - } - output.push(ts.sys.newLine); - } - } - for (var _b = 0, output_1 = output; _b < output_1.length; _b++) { - var line = output_1[_b]; - ts.sys.write(line); - } - return; - function getParamType(option) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - function makePadding(paddingLength) { - return Array(paddingLength + 1).join(" "); - } - } - ts.printHelp = printHelp; + ts.getDiagnosticText = getDiagnosticText; /** * Reads the config file, reports errors if any and exits if the config file cannot be found */ @@ -26475,7 +26482,7 @@ var ts; /** @internal */ function convertToTSConfig(configParseResult, configFileName, host) { var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames); - var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); + var files = ts.map(ts.filter(configParseResult.fileNames, (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? function (_) { return true; } : matchesSpecs(configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, configParseResult.configFileSpecs.validatedExcludeSpecs, host)), function (f) { return ts.getRelativePathFromFile(ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), ts.getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName); }); var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames }); var config = __assign(__assign({ compilerOptions: __assign(__assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) { var _a; @@ -26496,12 +26503,12 @@ var ts; return undefined; return specs; } - function matchesSpecs(path, includeSpecs, excludeSpecs) { + function matchesSpecs(path, includeSpecs, excludeSpecs, host) { if (!includeSpecs) return function (_) { return true; }; - var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, ts.sys.useCaseSensitiveFileNames, ts.sys.getCurrentDirectory()); - var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, ts.sys.useCaseSensitiveFileNames); - var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, ts.sys.useCaseSensitiveFileNames); + var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); }; @@ -26678,6 +26685,35 @@ var ts; } } ts.generateTSConfig = generateTSConfig; + /* @internal */ + function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) { + var result = {}; + var optionsNameMap = getOptionNameMap().optionNameMap; + for (var name in options) { + if (ts.hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths; + function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) { + if (option) { + if (option.type === "list") { + var values = value; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value); + } + } + return value; + } /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -27128,7 +27164,7 @@ var ts; } function normalizeNonListOptionValue(option, basePath, value) { if (option.isFilePath) { - value = ts.normalizePath(ts.combinePaths(basePath, value)); + value = ts.getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } @@ -28912,7 +28948,11 @@ var ts; ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface"; ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod"; })(ContainerFlags || (ContainerFlags = {})); - var flowNodeCreated = ts.identity; + function initFlowNode(node) { + ts.Debug.attachFlowNodeDebugInfo(node); + return node; + } + var flowNodeCreated = initFlowNode; var binder = createBinder(); function bindSourceFile(file, options) { ts.performance.mark("beforeBind"); @@ -28976,6 +29016,9 @@ var ts; symbolCount = 0; skipTransformFlagAggregation = file.isDeclarationFile; Symbol = ts.objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + ts.Debug.attachFlowNodeDebugInfo(unreachableFlow); + ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -29331,7 +29374,7 @@ var ts; // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) { currentFlow.node = node; } @@ -29343,7 +29386,7 @@ var ts; currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = ts.identity; + flowNodeCreated = initFlowNode; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~2816 /* ReachabilityAndEmitFlags */; @@ -29512,9 +29555,6 @@ var ts; case 309 /* JSDocEnumTag */: bindJSDocTypeAlias(node); break; - case 307 /* JSDocClassTag */: - bindJSDocClassTag(node); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case 288 /* SourceFile */: { bindEachFunctionsFirst(node.statements); @@ -29554,9 +29594,8 @@ var ts; function isNarrowableReference(expr) { return expr.kind === 75 /* Identifier */ || expr.kind === 103 /* ThisKeyword */ || expr.kind === 101 /* SuperKeyword */ || (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - ts.isElementAccessExpression(expr) && - ts.isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + ts.isOptionalChain(expr); } function hasNarrowableArgument(expr) { if (expr.arguments) { @@ -29613,10 +29652,10 @@ var ts; return isNarrowableReference(expr); } function createBranchLabel() { - return { flags: 4 /* BranchLabel */, antecedents: undefined }; + return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined }); } function createLoopLabel() { - return { flags: 8 /* LoopLabel */, antecedents: undefined }; + return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined }); } function setFlowNodeReferenced(flow) { // On first reference we set the Referenced flag, thereafter we set the Shared flag @@ -29637,7 +29676,7 @@ var ts; } if (expression.kind === 105 /* TrueKeyword */ && flags & 64 /* FalseCondition */ || expression.kind === 90 /* FalseKeyword */ && flags & 32 /* TrueCondition */) { - if (!ts.isOptionalChainRoot(expression.parent)) { + if (!ts.isExpressionOfOptionalChainRoot(expression)) { return unreachableFlow; } } @@ -29862,7 +29901,7 @@ var ts; // as possible antecedents of the start of the `catch` or `finally` blocks. // Don't bother intercepting the call if there's no finally or catch block that needs the information if (node.catchClause || node.finallyBlock) { - flowNodeCreated = function (node) { return (tryPriors.push(node), node); }; + flowNodeCreated = function (node) { return (tryPriors.push(node), initFlowNode(node)); }; } bind(node.tryBlock); flowNodeCreated = oldFlowNodeCreated; @@ -29926,7 +29965,7 @@ var ts; // // extra edges that we inject allows to control this behavior // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - var preFinallyFlow = { flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }; + var preFinallyFlow = initFlowNode({ flags: 4096 /* PreFinally */, antecedent: preFinallyPrior, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); bind(node.finallyBlock); @@ -29993,7 +30032,7 @@ var ts; bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, ts.Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | 536870912 /* HasComputedFlags */; @@ -30583,7 +30622,7 @@ var ts; var host = ts.getJSDocHost(typeAlias); container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file; blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: 2 /* Start */ }; + currentFlow = initFlowNode({ flags: 2 /* Start */ }); parent = typeAlias; bind(typeAlias.typeExpression); var declName = ts.getNameOfDeclaration(typeAlias); @@ -31006,6 +31045,8 @@ var ts; case 302 /* JSDocTypeLiteral */: case 185 /* MappedType */: return bindAnonymousTypeWorker(node); + case 307 /* JSDocClassTag */: + return bindJSDocClassTag(node); case 192 /* ObjectLiteralExpression */: return bindObjectLiteralExpression(node); case 200 /* FunctionExpression */: @@ -31225,7 +31266,8 @@ var ts; var flags = ts.exportAssignmentIsAlias(node) ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */; - declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node) { ts.Debug.assert(ts.isInJSFile(node)); @@ -31314,6 +31356,10 @@ var ts; } function bindObjectDefinePrototypeProperty(node) { var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } /** @@ -31388,7 +31434,7 @@ var ts; } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */); } return namespaceSymbol; @@ -32889,12 +32935,6 @@ var ts; CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions"; CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp"; })(CheckMode || (CheckMode = {})); - var ContextFlags; - (function (ContextFlags) { - ContextFlags[ContextFlags["None"] = 0] = "None"; - ContextFlags[ContextFlags["Signature"] = 1] = "Signature"; - ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints"; - })(ContextFlags || (ContextFlags = {})); var AccessFlags; (function (AccessFlags) { AccessFlags[AccessFlags["None"] = 0] = "None"; @@ -33033,9 +33073,6 @@ var ts; var requireSymbol = createSymbol(4 /* Property */, "require"); /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ var apparentArgumentCount; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - var pooledOptionalTypeResult = { isOptional: false, type: undefined }; // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -33154,9 +33191,9 @@ var ts; }, getAugmentedPropertiesOfType: getAugmentedPropertiesOfType, getRootSymbols: getRootSymbols, - getContextualType: function (nodeIn) { + getContextualType: function (nodeIn, contextFlags) { var node = ts.getParseTreeNode(nodeIn, ts.isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: function (nodeIn) { var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike); @@ -33205,7 +33242,7 @@ var ts; getEmitResolver: getEmitResolver, getExportsOfModule: getExportsOfModuleAsArray, getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule, - getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments), + getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments), getAmbientModules: getAmbientModules, getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt, isOptionalParameter: function (nodeIn) { @@ -33390,10 +33427,10 @@ var ts; markerSubType.constraint = markerSuperType; var markerOtherType = createTypeParameter(); var noTypePredicate = createTypePredicate(1 /* Identifier */, "<>", 0, anyType); - var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); + var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); var iterationTypesCache = ts.createMap(); // cache for common IterationTypes instances var noIterationTypes = { @@ -33546,7 +33583,7 @@ var ts; var chosenpragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma; file.localJsxFactory = ts.parseIsolatedEntityName(chosenpragma.arguments.factory, languageVersion); if (file.localJsxFactory) { - return file.localJsxNamespace = getFirstIdentifier(file.localJsxFactory).escapedText; + return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText; } } } @@ -33556,7 +33593,7 @@ var ts; if (compilerOptions.jsxFactory) { _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion); if (_jsxFactoryEntity) { - _jsxNamespace = getFirstIdentifier(_jsxFactoryEntity).escapedText; + _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText; } } else if (compilerOptions.reactNamespace) { @@ -34744,7 +34781,12 @@ var ts; ts.addRelatedInfo(err, ts.createDiagnosticForNode(exportAssignment, ts.Diagnostics.This_module_is_declared_with_using_export_and_can_only_be_used_with_a_default_import_when_using_the_0_flag, compilerOptionName)); } else { - error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, symbolToString(moduleSymbol), symbolToString(node.symbol)); + } + else { + error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } } } else if (hasSyntheticDefault) { @@ -34848,7 +34890,12 @@ var ts; } } else { - error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + if (moduleSymbol.exports && moduleSymbol.exports.has("default" /* Default */)) { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName); + } + else { + error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } } return symbol; @@ -35024,7 +35071,7 @@ var ts; var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0); var symbol; if (name.kind === 75 /* Identifier */) { - var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(getFirstIdentifier(name)); + var message = meaning === namespaceMeaning ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name)); var symbolFromJSPrototype = ts.isInJSFile(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined; symbol = resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true); if (!symbol) { @@ -35987,7 +36034,7 @@ var ts; // Type Reference or TypeAlias entity = Identifier meaning = 788968 /* Type */; } - var firstIdentifier = getFirstIdentifier(entityName); + var firstIdentifier = ts.getFirstIdentifier(entityName); var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false); // Verify if the symbol is accessible return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || { @@ -36842,7 +36889,7 @@ var ts; if (!context.tracker.trackSymbol) return; // get symbol of the first identifier of the entityName - var firstIdentifier = getFirstIdentifier(accessExpression); + var firstIdentifier = ts.getFirstIdentifier(accessExpression); var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); if (name) { context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */); @@ -37611,7 +37658,7 @@ var ts; // so we don't even have placeholders to fill in. if (ts.length(realMembers)) { var localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & 16 /* Function */)); } if (ts.length(mergedMembers)) { var localName = getInternalSymbolName(symbol, symbolName); @@ -37822,7 +37869,11 @@ var ts; case 254 /* ImportClause */: addResult(ts.createImportDeclaration( /*decorators*/ undefined, - /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + /*modifiers*/ undefined, ts.createImportClause(ts.createIdentifier(localName), /*namedBindings*/ undefined), + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 255 /* NamespaceImport */: addResult(ts.createImportDeclaration( @@ -37834,7 +37885,7 @@ var ts; /*decorators*/ undefined, /*modifiers*/ undefined, ts.createImportClause(/*importClause*/ undefined, ts.createNamedImports([ ts.createImportSpecifier(localName !== verbatimTargetName ? ts.createIdentifier(verbatimTargetName) : undefined, ts.createIdentifier(localName)) - ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent, context))), 0 /* None */); + ])), ts.createLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */); break; case 261 /* ExportSpecifier */: // does not use localName because the symbol name in this case refers to the name in the exports table, @@ -38103,7 +38154,7 @@ var ts; return ts.updateImportTypeNode(node, ts.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf); } if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) { - var leftmost = getFirstIdentifier(node); + var leftmost = ts.getFirstIdentifier(node); var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true); if (sym) { includePrivateSymbol(sym); @@ -38526,7 +38577,7 @@ var ts; if (ts.isInternalModuleImportEqualsDeclaration(declaration)) { // Add the referenced top container visible var internalModuleReference = declaration.moduleReference; - var firstIdentifier = getFirstIdentifier(internalModuleReference); + var firstIdentifier = ts.getFirstIdentifier(internalModuleReference); var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false); var id = importSymbol && "" + getSymbolId(importSymbol); if (importSymbol && !visited.has(id)) { @@ -39286,7 +39337,7 @@ var ts; // Handle variable, parameter or property if (!pushTypeResolution(symbol, 0 /* Type */)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39354,7 +39405,7 @@ var ts; } if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & 512 /* ValueModule */) { + if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -39437,7 +39488,9 @@ var ts; } else { ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter)) { + errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -39673,6 +39726,7 @@ var ts; // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol) { var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 245 /* InterfaceDeclaration */); + ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } // The local type parameters are the combined set of type parameters from all declarations of the class, @@ -39703,7 +39757,7 @@ var ts; var signatures = getSignaturesOfType(type, 1 /* Construct */); if (signatures.length === 1) { var s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -40540,8 +40594,8 @@ var ts; var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]); resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments); } - function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, hasRestParameter, hasLiteralTypes) { - var sig = new Signature(checker); + function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) { + var sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -40549,15 +40603,13 @@ var ts; sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; } function cloneSignature(sig) { var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -40569,13 +40621,17 @@ var ts; result.mapper = undefined; return result; } + function getOptionalCallSignature(signature) { + return signatureIsOptionalCall(signature) ? signature : + (signature.optionalCallSignatureCache || (signature.optionalCallSignatureCache = createOptionalCallSignature(signature))); + } function createOptionalCallSignature(signature) { var result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= 4 /* IsOptionalCall */; return result; } function getExpandedParameters(sig) { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { var restIndex_1 = sig.parameters.length - 1; var restParameter = sig.parameters[restIndex_1]; var restType = getTypeOfSymbol(restParameter); @@ -40600,7 +40656,7 @@ var ts; var baseConstructorType = getBaseConstructorTypeOfClass(classType); var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)]; } var baseTypeNode = getBaseTypeNodeOfClass(classType); var isJavaScript = ts.isInJSFile(baseTypeNode); @@ -40764,11 +40820,9 @@ var ts; var params = combineUnionParameters(left, right); var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - var hasRestParam = left.hasRestParameter || right.hasRestParameter; - var hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, minArgCount, hasRestParam, hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 3 /* PropagatingFlags */); result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]); return result; } @@ -40941,7 +40995,7 @@ var ts; var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray; if (symbol.flags & 16 /* Function */) { constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 3 /* PropagatingFlags */) : undefined; })); } if (!constructSignatures.length) { @@ -41881,7 +41935,7 @@ var ts; var links = getNodeLinks(declaration); if (!links.resolvedSignature) { var parameters = []; - var hasLiteralTypes = false; + var flags = 0 /* None */; var minArgumentCount = 0; var thisParameter = void 0; var hasThisParameter = false; @@ -41912,7 +41966,7 @@ var ts; parameters.push(paramSymbol); } if (type && type.kind === 186 /* LiteralType */) { - hasLiteralTypes = true; + flags |= 2 /* HasLiteralTypes */; } // Record a new minimum argument count if this is not an optional parameter var isOptionalParameter_1 = isOptionalJSDocParameterTag(param) || @@ -41938,9 +41992,11 @@ var ts; getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol)) : undefined; var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - var hasRestLikeParameter = ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= 1 /* HasRestParameter */; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, - /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags); } return links.resolvedSignature; } @@ -42083,8 +42139,8 @@ var ts; signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) : getReturnTypeFromAnnotation(signature.declaration) || (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signatureIsOptionalCall(signature)) { + type = addOptionalTypeMarker(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -42140,7 +42196,7 @@ var ts; return tryGetRestTypeOfSignature(signature) || anyType; } function tryGetRestTypeOfSignature(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, 1 /* Number */); @@ -42514,7 +42570,7 @@ var ts; errorType; } if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) { - var jsdocType = getTypeFromJSAlias(node, symbol); + var jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -42527,18 +42583,25 @@ var ts; return errorType; } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function fakes special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node, symbol) { + function getTypeFromJSDocValueReference(node, symbol) { var valueType = getTypeOfSymbol(symbol); - var typeType = valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + var typeType = valueType; + if (symbol.valueDeclaration) { + var decl = ts.getRootDeclaration(symbol.valueDeclaration); + var isRequireAlias = ts.isVariableDeclaration(decl) + && decl.initializer + && ts.isCallExpression(decl.initializer) + && ts.isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ true) + && valueType.symbol; + if (isRequireAlias) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable, substitute) { if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === typeVariable) { @@ -44079,7 +44142,7 @@ var ts; } function getAliasSymbolForTypeNode(node) { var host = node.parent; - while (ts.isParenthesizedTypeNode(host)) { + while (ts.isParenthesizedTypeNode(host) || ts.isTypeOperatorNode(host) && host.operator === 137 /* ReadonlyKeyword */) { host = host.parent; } return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -44494,7 +44557,7 @@ var ts; // See GH#17600. var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.hasRestParameter, signature.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 3 /* PropagatingFlags */); result.target = signature; result.mapper = mapper; return result; @@ -45382,7 +45445,7 @@ var ts; */ function isAnySignature(s) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } /** @@ -48067,37 +48130,19 @@ var ts; function addOptionalTypeMarker(type) { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type) { + return type !== optionalType; + } function removeOptionalTypeMarker(type) { - return strictNullChecks ? filterType(type, function (t) { return t !== optionalType; }) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } function propagateOptionalTypeMarker(type, wasOptional) { return wasOptional ? addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional, type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - function checkOptionalExpression(parent, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - var isOptional = false; - var type = checkExpression(expression); - if (ts.isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - var nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType, expression) { + return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** * Is source potentially coercible to target type under `==`. @@ -48732,10 +48777,7 @@ var ts; // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, 1 /* NakedTypeVariable */); return; } source = getUnionType(sources); @@ -48835,10 +48877,7 @@ var ts; else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) { var empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - var savePriority = priority; - priority |= 32 /* LiteralKeyof */; - inferFromTypes(empty, target.type); - priority = savePriority; + inferWithPriority(empty, target.type, 32 /* LiteralKeyof */); contravariant = !contravariant; } else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) { @@ -48890,6 +48929,12 @@ var ts; } } } + function inferWithPriority(source, target, newPriority) { + var savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } function invokeOnce(source, target, action) { var key = source.id + "," + target.id; var status = visited && visited.get(key); @@ -48955,6 +49000,18 @@ var ts; } return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types) { + var typeVariable; + for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { + var type = types_13[_i]; + var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); }); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } function inferToMultipleTypes(source, targets, targetFlags) { var typeVariableCount = 0; if (targetFlags & 1048576 /* Union */) { @@ -48984,6 +49041,16 @@ var ts; } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -49015,15 +49082,12 @@ var ts; // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) { - var savePriority = priority; - priority |= 1 /* NakedTypeVariable */; for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) { var t = targets_4[_b]; if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, 1 /* NakedTypeVariable */); } } - priority = savePriority; } } function inferToMappedType(source, target, constraintType) { @@ -49044,14 +49108,12 @@ var ts; if (inference && !inference.isFixed) { var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - var savePriority = priority; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - priority |= ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? - 4 /* PartialHomomorphicMappedType */ : 2 /* HomomorphicMappedType */; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 1048576 /* NonInferrableType */ ? + 4 /* PartialHomomorphicMappedType */ : + 2 /* HomomorphicMappedType */); } } return true; @@ -49059,10 +49121,7 @@ var ts; if (constraintType.flags & 262144 /* TypeParameter */) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - var savePriority = priority; - priority |= 8 /* MappedTypeConstraint */; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, 8 /* MappedTypeConstraint */); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -49440,6 +49499,15 @@ var ts; } return false; } + function optionalChainContainsReference(source, target) { + while (ts.isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -49560,8 +49628,8 @@ var ts; } function getTypeFactsOfTypes(types) { var result = 0 /* None */; - for (var _i = 0, types_13 = types; _i < types_13.length; _i++) { - var t = types_13[_i]; + for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { + var t = types_14[_i]; result |= getTypeFacts(t); } return result; @@ -49930,8 +49998,8 @@ var ts; } function isEvolvingArrayTypeList(types) { var hasEvolvingArrayType = false; - for (var _i = 0, types_14 = types; _i < types_14.length; _i++) { - var t = types_14[_i]; + for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { + var t = types_15[_i]; if (!(t.flags & 131072 /* Never */)) { if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) { return false; @@ -50012,9 +50080,18 @@ var ts; // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - var funcType = node.parent.kind === 225 /* ExpressionStatement */ ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== 101 /* SuperKeyword */ ? checkOptionalExpression(node, node.expression).type : - undefined; + var funcType = void 0; + if (node.parent.kind === 225 /* ExpressionStatement */) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== 101 /* SuperKeyword */) { + if (ts.isOptionalChain(node)) { + funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */); var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -50027,6 +50104,13 @@ var ts; return !!(getTypePredicateOfSignature(signature) || signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */); } + function getTypePredicateArgument(predicate, callExpression) { + if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { + return callExpression.arguments[predicate.parameterIndex]; + } + var invokedExpression = ts.skipParentheses(callExpression.expression); + return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined; + } function reportFlowControlError(node) { var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock); var sourceFile = ts.getSourceFileOfNode(node); @@ -50042,6 +50126,11 @@ var ts; function isUnlockedReachableFlowNode(flow) { return !(flow.flags & 4096 /* PreFinally */ && flow.lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr) { + var node = ts.skipParentheses(expr); + return node.kind === 90 /* FalseKeyword */ || node.kind === 208 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) || + node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right)); + } function isReachableFlowNodeWorker(flow, noCacheCheck) { while (true) { if (flow === lastFlowNode) { @@ -50061,8 +50150,17 @@ var ts; } else if (flags & 512 /* Call */) { var signature = getEffectsSignature(flow.node); - if (signature && getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { - return false; + if (signature) { + var predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === 3 /* AssertsIdentifier */) { + var predicateArgument = flow.node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) { + return false; + } } flow = flow.antecedent; } @@ -50296,6 +50394,9 @@ var ts; } function narrowTypeByAssertion(type, expr) { var node = ts.skipParentheses(expr); + if (node.kind === 90 /* FalseKeyword */) { + return unreachableNeverType; + } if (node.kind === 208 /* BinaryExpression */) { if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) { return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right); @@ -50314,7 +50415,7 @@ var ts; var flowType = getTypeAtFlowNode(flow.antecedent); var type = getTypeFromFlowType(flowType); var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === 3 /* AssertsIdentifier */ ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -50385,17 +50486,27 @@ var ts; if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); - } else if (expr.kind === 203 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); }); + } + else if (expr.kind === 203 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); }); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); }); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } + else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { + return unreachableNeverType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -50537,6 +50648,9 @@ var ts; if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); }); } @@ -50585,6 +50699,14 @@ var ts; if (isMatchingReference(reference, right_1)) { return narrowTypeByEquality(type, operator_1, left_1, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue); + } + else if (optionalChainContainsReference(right_1, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left_1, declaredType)) { return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); }); } @@ -50608,6 +50730,15 @@ var ts; } return type; } + function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + var effectiveTrue = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */ ? assumeTrue : !assumeTrue; + var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */; + var valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? 262144 /* EQUndefinedOrNull */ : 65536 /* EQUndefined */)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeByEquality(type, operator, value, assumeTrue) { if (type.flags & 1 /* Any */) { return type; @@ -50655,8 +50786,14 @@ var ts; } function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { + assumeTrue = !assumeTrue; + } var target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -50664,9 +50801,6 @@ var ts; } return type; } - if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) { - assumeTrue = !assumeTrue; - } if (type.flags & 1 /* Any */ && literal.text === "function") { return type; } @@ -50699,6 +50833,10 @@ var ts; return type; } } + function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) { + var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type; + } function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -50831,6 +50969,9 @@ var ts; function narrowTypeByInstanceof(type, expr, assumeTrue) { var left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -50903,39 +51044,28 @@ var ts; } function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) { - var predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + var predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) { + return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - var invokedExpression = ts.skipParentheses(callExpression.expression); - if (ts.isAccessExpression(invokedExpression) && predicate.type) { - var possibleReference = ts.skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } // Narrow the given type based on the given expression having the assumed boolean value. The returned type // will be a subtype or the same type as the argument. function narrowType(type, expr, assumeTrue) { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (ts.isOptionalChainRoot(expr.parent) || + if (ts.isExpressionOfOptionalChainRoot(expr) || ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -51996,18 +52126,22 @@ var ts; return undefined; } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget, arg) { + function getContextualTypeForArgument(callTarget, arg, contextFlags) { var args = getEffectiveCallArguments(callTarget); var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget, argIndex) { + function getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags) { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & 4 /* Completion */ && signature.target) { + var baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } function getContextualTypeForSubstitutionExpression(template, substitutionExpression) { @@ -52366,7 +52500,7 @@ var ts; } /* falls through */ case 196 /* NewExpression */: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case 198 /* TypeAssertionExpression */: case 216 /* AsExpression */: return ts.isConstTypeReference(parent.type) ? undefined : getTypeFromTypeNode(parent.type); @@ -52581,8 +52715,8 @@ var ts; } var signatureList; var types = type.types; - for (var _i = 0, types_15 = types; _i < types_15.length; _i++) { - var current = types_15[_i]; + for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { + var current = types_16[_i]; var signature = getContextualCallSignature(current, node); if (signature) { if (!signatureList) { @@ -53579,8 +53713,8 @@ var ts; function symbolHasNonMethodDeclaration(symbol) { return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); }); } - function checkNonNullExpression(node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { - return checkNonNullType(checkExpression(node), node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); + function checkNonNullExpression(node) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type) { return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */); @@ -53588,22 +53722,34 @@ var ts; function getNonNullableTypeIfNeeded(type) { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType(type, node, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic) { + function reportObjectPossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Object_is_possibly_null_or_undefined : + ts.Diagnostics.Object_is_possibly_undefined : + ts.Diagnostics.Object_is_possibly_null); + } + function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) { + error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ? + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null); + } + function checkNonNullTypeWithReporter(type, node, reportError) { if (strictNullChecks && type.flags & 2 /* Unknown */) { error(node, ts.Diagnostics.Object_is_of_type_unknown); return errorType; } var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */; if (kind) { - error(node, kind & 32768 /* Undefined */ ? kind & 65536 /* Null */ ? - (nullOrUndefinedDiagnostic || ts.Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || ts.Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || ts.Diagnostics.Object_is_possibly_null)); + reportError(node, kind); var t = getNonNullableType(type); return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t; } return type; } + function checkNonNullType(type, node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } function checkNonNullNonVoidType(type, node) { var nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) { @@ -53612,10 +53758,16 @@ var ts; return nonNullType; } function checkPropertyAccessExpression(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + function checkPropertyAccessChain(node) { + var leftType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), nonOptionalType !== leftType); } function checkQualifiedName(node) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node) { while (node.parent.kind === 199 /* ParenthesizedExpression */) { @@ -53623,8 +53775,7 @@ var ts; } return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node, left, right) { - var _a = checkOptionalExpression(node, left), isOptional = _a.isOptional, leftType = _a.type; + function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) { var parentSymbol = getNodeLinks(left).resolvedSymbol; var assignmentKind = ts.getAssignmentTargetKind(node); var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -53677,7 +53828,7 @@ var ts; } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) { // Only compute control flow type if this is a property access expression that isn't an @@ -53999,7 +54150,15 @@ var ts; return false; } function checkIndexedAccess(node) { - var _a = checkOptionalExpression(node, node.expression), isOptional = _a.isOptional, exprType = _a.type; + return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + function checkElementAccessChain(node) { + var exprType = checkExpression(node.expression); + var nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), nonOptionalType !== exprType); + } + function checkElementAccessExpression(node, exprType) { var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; var indexExpression = node.argumentExpression; var indexType = checkExpression(indexExpression); @@ -54015,7 +54174,7 @@ var ts; 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) : 0 /* None */; var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) { if (expressionType === errorType) { @@ -54116,7 +54275,7 @@ var ts; lastSymbol = symbol; // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -54127,7 +54286,7 @@ var ts; else { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, isOptionalCall ? getOptionalCallSignature(signature) : signature); } } function isSpreadArgument(arg) { @@ -54422,7 +54581,19 @@ var ts; // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. var thisArgumentNode = getThisArgumentOfCall(node); - var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + var thisArgumentType = void 0; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (ts.isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (ts.isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } var errorNode = reportErrors ? (thisArgumentNode || node) : undefined; var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) { @@ -54649,7 +54820,7 @@ var ts; if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) { var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount]; if (paramDecl) { - related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(getFirstIdentifier(paramDecl.name)) : undefined); + related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided : ts.Diagnostics.An_argument_for_0_was_not_provided, !paramDecl.name ? argCount : !ts.isBindingPattern(paramDecl.name) ? ts.idText(ts.getFirstIdentifier(paramDecl.name)) : undefined); } } if (min < argCount && argCount < max) { @@ -54975,34 +55146,34 @@ var ts; var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max; var parameters = []; var _loop_15 = function (i) { - var symbols = ts.mapDefined(candidates, function (_a) { - var parameters = _a.parameters, hasRestParameter = _a.hasRestParameter; - return hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : ts.last(parameters) : - i < parameters.length ? parameters[i] : undefined; - }); + var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined; }); ts.Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); }))); }; for (var i = 0; i < maxNonRestParam; i++) { _loop_15(i); } - var restParameterSymbols = ts.mapDefined(candidates, function (c) { return c.hasRestParameter ? ts.last(c.parameters) : undefined; }); - var hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; }); + var flags = 0 /* None */; + if (restParameterSymbols.length !== 0) { var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= 1 /* HasRestParameter */; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= 2 /* HasLiteralTypes */; } return createSignature(candidates[0].declaration, /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`. thisParameter, parameters, /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), - /*typePredicate*/ undefined, minArgumentCount, hasRestParameter, - /*hasLiteralTypes*/ candidates.some(function (c) { return c.hasLiteralTypes; })); + /*typePredicate*/ undefined, minArgumentCount, flags); } function getNumNonRestParameters(signature) { var numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources, types) { return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */)); @@ -55083,7 +55254,17 @@ var ts; } return resolveUntypedCall(node); } - var _b = checkOptionalExpression(node, node.expression, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined), isOptional = _b.isOptional, funcType = _b.type; + var isOptional; + var funcType = checkExpression(node.expression); + if (ts.isCallChain(node)) { + var nonOptionalType = getOptionalExpressionType(funcType, node.expression); + isOptional = nonOptionalType !== funcType; + funcType = nonOptionalType; + } + else { + isOptional = false; + } + funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError); if (funcType === silentNeverType) { return silentNeverSignature; } @@ -55305,8 +55486,8 @@ var ts; if (apparentType.flags & 1048576 /* Union */) { var types = apparentType.types; var hasSignatures = false; - for (var _i = 0, types_16 = types; _i < types_16.length; _i++) { - var constituent = types_16[_i]; + for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { + var constituent = types_17[_i]; var signatures = getSignaturesOfType(constituent, kind); if (signatures.length !== 0) { hasSignatures = true; @@ -55465,9 +55646,7 @@ var ts; return createSignature(declaration, /*typeParameters*/ undefined, /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, - /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false); + /*returnTypePredicate*/ undefined, 1, 0 /* None */); } function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) { if (isJsxIntrinsicIdentifier(node.tagName)) { @@ -55500,7 +55679,7 @@ var ts; function isPotentiallyUncalledDecorator(decorator, signatures) { return signatures.length && ts.every(signatures, function (signature) { return signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature); }); } @@ -55881,7 +56060,7 @@ var ts; return type; } function getParameterNameAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -55898,11 +56077,11 @@ var ts; return tryGetTypeAtPosition(signature, pos) || anyType; } function tryGetTypeAtPosition(signature, pos) { - var paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -55937,7 +56116,7 @@ var ts; } function getParameterCount(signature) { var length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -55946,7 +56125,7 @@ var ts; return length; } function getMinArgumentCount(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { var minLength = restType.target.minLength; @@ -55958,14 +56137,14 @@ var ts; return signature.minArgumentCount; } function hasEffectiveRestParameter(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } return false; } function getEffectiveRestType(signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -55982,7 +56161,7 @@ var ts; return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType; } function inferFromAnnotatedParameters(signature, context, inferenceContext) { - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -56015,7 +56194,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(signature.thisParameter, getTypeOfSymbol(context.thisParameter)); } } - var len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (var i = 0; i < len; i++) { var parameter = signature.parameters[i]; if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56023,7 +56202,7 @@ var ts; assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. var parameter = ts.last(signature.parameters); if (isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -56428,7 +56607,7 @@ var ts; return links.contextFreeType; } var returnType = getReturnTypeFromBody(node, checkMode); - var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */); var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined); returnOnlyType.objectFlags |= 1048576 /* NonInferrableType */; return links.contextFreeType = returnOnlyType; @@ -56761,8 +56940,8 @@ var ts; } if (type.flags & 3145728 /* UnionOrIntersection */) { var types = type.types; - for (var _i = 0, types_17 = types; _i < types_17.length; _i++) { - var t = types_17[_i]; + for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { + var t = types_18[_i]; if (maybeTypeOfKind(t, kind)) { return true; } @@ -57761,7 +57940,18 @@ var ts; // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (ts.isCallExpression(expr) && expr.expression.kind !== 101 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - var _a = checkOptionalExpression(expr, expr.expression), isOptional = _a.isOptional, funcType = _a.type; + var isOptional = void 0; + var funcType = void 0; + if (ts.isCallChain(expr)) { + funcType = checkExpression(expr.expression); + var nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + isOptional = funcType !== nonOptionalType; + funcType = checkNonNullType(nonOptionalType, expr.expression); + } + else { + isOptional = false; + funcType = checkNonNullExpression(expr.expression); + } var signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); @@ -58018,7 +58208,7 @@ var ts; } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -59193,7 +59383,7 @@ var ts; return; } // Verify there is no local declaration that could collide with the promise constructor. - var rootName = promiseConstructorName && getFirstIdentifier(promiseConstructorName); + var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName); var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */); if (collidingSymbol) { error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName)); @@ -59250,7 +59440,7 @@ var ts; function markEntityNameOrEntityExpressionAsReference(typeName) { if (!typeName) return; - var rootName = getFirstIdentifier(typeName); + var rootName = ts.getFirstIdentifier(typeName); var meaning = (typeName.kind === 75 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */; var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true); if (rootSymbol @@ -59290,8 +59480,8 @@ var ts; } function getEntityNameForDecoratorMetadataFromTypeList(types) { var commonEntityName; - for (var _i = 0, types_18 = types; _i < types_18.length; _i++) { - var typeNode = types_18[_i]; + for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { + var typeNode = types_19[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -61066,10 +61256,7 @@ var ts; firstDefaultClause = clause; } else { - var sourceFile = ts.getSourceFileOfNode(node); - var start = ts.skipTrivia(sourceFile.text, clause.pos); - var end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -61090,6 +61277,9 @@ var ts; } } ts.forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, ts.Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -61641,15 +61831,13 @@ var ts; } } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & 98304 /* Accessor */) { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */)); + errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & 98304 /* Accessor */) { @@ -62155,22 +62343,6 @@ var ts; break; } } - function getFirstIdentifier(node) { - switch (node.kind) { - case 75 /* Identifier */: - return node; - case 152 /* QualifiedName */: - do { - node = node.left; - } while (node.kind !== 75 /* Identifier */); - return node; - case 193 /* PropertyAccessExpression */: - do { - node = node.expression; - } while (node.kind !== 75 /* Identifier */); - return node; - } - } function getFirstNonModuleExportsIdentifier(node) { switch (node.kind) { case 75 /* Identifier */: @@ -62300,7 +62472,7 @@ var ts; if (target !== unknownSymbol) { if (target.flags & 111551 /* Value */) { // Target is a value symbol, check that it is not hidden by a local declaration with the same name - var moduleName = getFirstIdentifier(node.moduleReference); + var moduleName = ts.getFirstIdentifier(node.moduleReference); if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) { error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName)); } @@ -62367,7 +62539,7 @@ var ts; // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName)); } else { @@ -64673,10 +64845,10 @@ var ts; if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_type_alias_Consider_writing_0_Colon_1_Colon_2_instead, ts.getTextOfNode(parameter.name), typeToString(type), typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 128 /* StringLiteral */, /*strict*/ true)) { + if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -65559,7 +65731,7 @@ var ts; } function checkGrammarImportCallExpression(node) { if (moduleKind === ts.ModuleKind.ES2015) { - return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments); @@ -65629,6 +65801,18 @@ var ts; case 2 /* Next */: return "nextType"; } } + function signatureHasRestParameter(s) { + return !!(s.flags & 1 /* HasRestParameter */); + } + ts.signatureHasRestParameter = signatureHasRestParameter; + function signatureHasLiteralTypes(s) { + return !!(s.flags & 2 /* HasLiteralTypes */); + } + ts.signatureHasLiteralTypes = signatureHasLiteralTypes; + function signatureIsOptionalCall(s) { + return !!(s.flags & 4 /* IsOptionalCall */); + } + ts.signatureIsOptionalCall = signatureIsOptionalCall; })(ts || (ts = {})); var ts; (function (ts) { @@ -66562,7 +66746,9 @@ var ts; } ts.createPropertyAccess = createPropertyAccess; function updatePropertyAccess(node, expression, name) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -66600,7 +66786,9 @@ var ts; } ts.createElementAccess = createElementAccess; function updateElementAccess(node, expression, argumentExpression) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (ts.isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -66634,7 +66822,9 @@ var ts; } ts.createCall = createCall; function updateCall(node, expression, typeArguments, argumentsArray) { - ts.Debug.assert(!(node.flags & 32 /* OptionalChain */), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (ts.isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -67236,7 +67426,7 @@ var ts; var node = createSynthesizedNode(231 /* ForOfStatement */); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = ts.isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -68336,8 +68526,11 @@ var ts; (texts || (texts = [])).push(prependNode); break; case "internal" /* Internal */: - if (stripInternal) + if (stripInternal) { + if (!texts) + texts = []; break; + } // falls through case "text" /* Text */: (texts || (texts = [])).push(createUnparsedNode(section, node)); @@ -69759,7 +69952,7 @@ var ts; var conditionalPrecedence = ts.getOperatorPrecedence(209 /* ConditionalExpression */, 57 /* QuestionToken */); var emittedCondition = ts.skipPartiallyEmittedExpressions(condition); var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition); - if (ts.compareValues(conditionPrecedence, conditionalPrecedence) === -1 /* LessThan */) { + if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) { return ts.createParen(condition); } return condition; @@ -74202,8 +74395,8 @@ var ts; // Note when updating logic here also update getEntityNameForDecoratorMetadata // so that aliases can be marked as referenced var serializedUnion; - for (var _i = 0, types_19 = types; _i < types_19.length; _i++) { - var typeNode = types_19[_i]; + for (var _i = 0, types_20 = types; _i < types_20.length; _i++) { + var typeNode = types_20[_i]; while (typeNode.kind === 181 /* ParenthesizedType */) { typeNode = typeNode.type; // Skip parens if need be } @@ -75634,7 +75827,7 @@ var ts; // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer); + var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !ts.isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -87649,6 +87842,7 @@ var ts; var combinedStatements; if (ts.isSourceFileJS(currentSourceFile)) { combinedStatements = ts.createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax); } else { @@ -89420,7 +89614,11 @@ var ts; bundleBuildInfo.js = printer.bundleFileInfo; } function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) + return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) + emitSkipped = true; return; } var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; @@ -92174,8 +92372,8 @@ var ts; bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName }); writeLine(); } - for (var _d = 0, types_20 = types; _d < types_20.length; _d++) { - var directive = types_20[_d]; + for (var _d = 0, types_21 = types; _d < types_21.length; _d++) { + var directive = types_21[_d]; var pos = writer.getTextPos(); writeComment("/// "); if (bundleFileInfo) @@ -94445,6 +94643,8 @@ var ts; return resolutions; } ts.loadWithLocalCache = loadWithLocalCache; + /* @internal */ + ts.inferredTypesContainingFile = "__inferred type names__.ts"; /** * Determines if program structure is upto date or needs to be recreated */ @@ -94697,7 +94897,7 @@ var ts; if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); - var containingFilename = ts.combinePaths(containingDirectory, "__inferred type names__.ts"); + var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile); var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (var i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -96435,9 +96635,6 @@ var ts; else if (options.incremental && !options.outFile && !options.out && !options.configFilePath) { programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && ts.isIncrementalCompilation(options)) { - createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list if (options.composite) { @@ -97482,6 +97679,7 @@ var ts; ts.Debug.assert(state.seenAffectedFiles === undefined); state.seenAffectedFiles = ts.createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) { @@ -98212,7 +98410,7 @@ var ts; } var state = { fileInfos: fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && ts.arrayToMap(program.semanticDiagnosticsPerFile, function (value) { return toPath(ts.isString(value) ? value : value[0]); }, function (value) { return ts.isString(value) ? ts.emptyArray : value[1]; }), @@ -98248,33 +98446,6 @@ var ts; } } ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo; - function convertFromReusableCompilerOptions(options, toAbsolutePath) { - var result = {}; - var optionsNameMap = ts.getOptionNameMap().optionNameMap; - for (var name in options) { - if (ts.hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - function convertFromReusableCompilerOptionValue(option, value, toAbsolutePath) { - if (option) { - if (option.type === "list") { - var values = value; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value); - } - } - return value; - } function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) { return { getState: ts.notImplemented, @@ -98818,6 +98989,10 @@ var ts; // 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); + // When its a file with inferred types resolution, invalidate type reference directive resolution + if (containingFilePath.endsWith(ts.inferredTypesContainingFile)) { + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + } } }); }); @@ -99223,10 +99398,13 @@ var ts; // Simplify the full file path to something that can be resolved by Node. // If the module could be imported by a directory name, use that directory's name var moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!ts.startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) + var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { return undefined; + } // If the module was found in @types, get the actual Node package name var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName); @@ -99451,7 +99629,7 @@ var ts; /** Parses config file using System interface */ function parseConfigFileWithSystem(configFileName, optionsToExtend, system, reportDiagnostic) { var host = system; - host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(ts.sys, reportDiagnostic, diagnostic); }; + host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); }; var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217 return result; @@ -99475,7 +99653,7 @@ var ts; } ts.getErrorSummaryText = getErrorSummaryText; function listFiles(program, writeFileName) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { ts.forEach(program.getSourceFiles(), function (file) { writeFileName(file.fileName); }); @@ -99486,6 +99664,7 @@ var ts; * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options */ function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) { + var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; // First get and report any syntactic errors. var diagnostics = program.getConfigFileParsingDiagnostics().slice(); var configFileParsingDiagnosticsLength = diagnostics.length; @@ -99494,13 +99673,17 @@ var ts; // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + if (diagnostics.length === configFileParsingDiagnosticsLength) { + ts.addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - var emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + var emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: ts.emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics; ts.addRange(diagnostics, emitDiagnostics); ts.sortAndDeduplicateDiagnostics(diagnostics).forEach(reportDiagnostic); @@ -101392,30 +101575,25 @@ var ts; setupInitialBuild(state, cancellationToken); var reportQueue = true; var successfulProjects = 0; - var errorProjects = 0; while (true) { var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; - } } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ts.ExitStatus.DiagnosticsPresent_OutputsGenerated : - ts.ExitStatus.DiagnosticsPresent_OutputsSkipped : - ts.ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); }) + ? ts.ExitStatus.Success + : successfulProjects + ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated + : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state, project, onlyReferences) { var buildOrder = getBuildOrderFor(state, project, onlyReferences); @@ -101423,7 +101601,7 @@ var ts; return ts.ExitStatus.InvalidProject_OutputsSkipped; if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ts.ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped; } var options = state.options, host = state.host; var filesToDelete = options.dry ? [] : undefined; diff --git a/lib/zh-cn/diagnosticMessages.generated.json b/lib/zh-cn/diagnosticMessages.generated.json index 2eb27cd9054..062df5844c9 100644 --- a/lib/zh-cn/diagnosticMessages.generated.json +++ b/lib/zh-cn/diagnosticMessages.generated.json @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "函数实现缺失或未立即出现在声明之后。", "Function_implementation_name_must_be_0_2389": "函数实现名称必须为“{0}”。", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "由于函数不具有返回类型批注并且在它的一个返回表达式中得到直接或间接引用,因此它隐式具有返回类型 \"any\"。", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函数缺少结束返回语句,返回类型不包括 \"undefined\"。", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函数缺少结束 return 语句,返回类型不包括 \"undefined\"。", "Function_overload_must_be_static_2387": "函数重载必须为静态。", "Function_overload_must_not_be_static_2388": "函数重载不能为静态。", "Generate_get_and_set_accessors_95046": "生成 \"get\" 和 \"set\" 访问器", @@ -536,7 +536,7 @@ "JSX_elements_cannot_have_multiple_attributes_with_the_same_name_17001": "JSX 元素不能具有多个名称相同的特性。", "JSX_expressions_must_have_one_parent_element_2657": "JSX 表达式必须具有一个父元素。", "JSX_fragment_has_no_corresponding_closing_tag_17014": "JSX 片段没有相应的结束标记。", - "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂杂注时,不支持 JSX 片段", + "JSX_fragment_is_not_supported_when_using_an_inline_JSX_factory_pragma_17017": "使用内联 JSX 工厂 pragma 时,不支持 JSX 片段", "JSX_fragment_is_not_supported_when_using_jsxFactory_17016": "使用 --jsxFactory 时不支持 JSX 片段", "JSX_spread_child_must_be_an_array_type_2609": "JSX 扩展子属性必须为数组类型。", "Jump_target_cannot_cross_function_boundary_1107": "跳转目标不能跨越函数边界。", diff --git a/lib/zh-tw/diagnosticMessages.generated.json b/lib/zh-tw/diagnosticMessages.generated.json index bd1443da4fe..6496c4afa54 100644 --- a/lib/zh-tw/diagnosticMessages.generated.json +++ b/lib/zh-tw/diagnosticMessages.generated.json @@ -1,12 +1,12 @@ { - "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 修飾詞無法與匯入宣告並用。", - "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "'{0}' 修飾詞無法與介面宣告並用。", + "A_0_modifier_cannot_be_used_with_an_import_declaration_1079": "'{0}' 修飾元無法與匯入宣告並用。", + "A_0_modifier_cannot_be_used_with_an_interface_declaration_1045": "'{0}' 修飾元無法與介面宣告並用。", "A_0_parameter_must_be_the_first_parameter_2680": "'{0}' 參數必須為第一個參數。", "A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature_2463": "實作簽章中不得省略繫結模式參數。", "A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement_1105": "'break' 陳述式只可在封入的反覆項目或 switch 陳述式內使用。", "A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement_1116": "'break' 陳述式只可跳至封入之陳述式的標籤。", "A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments_2500": "類別只能實作具有選擇性型別引數的識別碼/限定名稱。", - "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "不具 'default' 修飾詞的類別宣告必須要有名稱。", + "A_class_declaration_without_the_default_modifier_must_have_a_name_1211": "不具 'default' 修飾元的類別宣告必須要有名稱。", "A_class_may_only_extend_another_class_2311": "每個類別只可擴充另一個類別。", "A_class_may_only_implement_another_class_or_interface_2422": "每個類別只可實作另一個類別或介面。", "A_class_member_cannot_have_the_0_keyword_1248": "類別成員不能含有 '{0}' 關鍵字。", @@ -25,8 +25,8 @@ "A_constructor_cannot_have_a_this_parameter_2681": "建構函式不能含有 'this' 參數。", "A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement_1104": "'continue' 陳述式只可在封入的反覆項目陳述式內使用。", "A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement_1115": "'continue' 陳述式只可跳至封入之反覆項目陳述式的標籤。", - "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "不得在現有環境內容中使用 'declare' 修飾詞。", - "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": ".d.ts 檔案中的最上層宣告需要 'declare' 修飾詞。", + "A_declare_modifier_cannot_be_used_in_an_already_ambient_context_1038": "不得在現有環境內容中使用 'declare' 修飾元。", + "A_declare_modifier_is_required_for_a_top_level_declaration_in_a_d_ts_file_1046": ".d.ts 檔案中的最上層宣告需要 'declare' 修飾元。", "A_decorator_can_only_decorate_a_method_implementation_not_an_overload_1249": "一個裝飾項目只能裝飾一項方法實作,而不能多載。", "A_default_clause_cannot_appear_more_than_once_in_a_switch_statement_1113": "'default' 子句在 'switch' 陳述式中不得出現一次以上。", "A_default_export_can_only_be_used_in_an_ECMAScript_style_module_1319": "預設匯出只能在 ECMAScript 樣式的模組中使用。", @@ -93,15 +93,15 @@ "Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression_2513": "無法透過 super 運算式存取類別 '{1}' 中的抽象方法 '{0}'。", "Abstract_methods_can_only_appear_within_an_abstract_class_1244": "抽象方法只可出現在抽象類別中。", "Abstract_property_0_in_class_1_cannot_be_accessed_in_the_constructor_2715": "無法從建構函式存取類別 '{1}' 中的抽象屬性 '{0}'。", - "Accessibility_modifier_already_seen_1028": "已有存取範圍修飾詞。", + "Accessibility_modifier_already_seen_1028": "已有存取範圍修飾元。", "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_0_to_unresolved_variable_90008": "對未解析的變數新增 '{0}.'", - "Add_all_missing_async_modifiers_95041": "新增缺少的所有 'async' 修飾詞", + "Add_all_missing_async_modifiers_95041": "新增缺少的所有 'async' 修飾元", "Add_all_missing_members_95022": "新增遺漏的所有成員", "Add_all_missing_super_calls_95039": "新增缺少的所有 super 呼叫", - "Add_async_modifier_to_containing_function_90029": "將 async 修飾詞新增至包含的函式", + "Add_async_modifier_to_containing_function_90029": "將 async 修飾元新增至包含的函式", "Add_braces_to_arrow_function_95059": "將大括號新增至箭號函式", "Add_definite_assignment_assertion_to_property_0_95020": "將明確指派判斷提示新增至屬性 '{0}'", "Add_definite_assignment_assertions_to_all_uninitialized_properties_95028": "為所有未初始化的屬性新增明確的指派判斷提示", @@ -119,7 +119,7 @@ "Adding_a_tsconfig_json_file_will_help_organize_projects_that_contain_both_TypeScript_and_JavaScript__5068": "新增 tsconfig.json 檔案有助於組織同時包含 TypeScript 及 JavaScript 檔案的專案。若要深入了解,請前往 https://aka.ms/tsconfig。", "Additional_Checks_6176": "其他檢查", "Advanced_Options_6178": "進階選項", - "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾詞。", + "All_declarations_of_0_must_have_identical_modifiers_2687": "'{0}' 的所有宣告都必須有相同修飾元。", "All_declarations_of_0_must_have_identical_type_parameters_2428": "'{0}' 的所有宣告都必須具有相同的類型參數。", "All_declarations_of_an_abstract_method_must_be_consecutive_2516": "抽象方法的所有宣告必須連續。", "All_destructured_elements_are_unused_6198": "不會使用所有未經結構化的項目。", @@ -145,20 +145,20 @@ "An_export_assignment_can_only_be_used_in_a_module_1231": "匯出指派只可用於模組中。", "An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements_2309": "匯出指派不得用於具有其他匯出項目的模組中。", "An_export_assignment_cannot_be_used_in_a_namespace_1063": "命名空間中不可使用匯出指派。", - "An_export_assignment_cannot_have_modifiers_1120": "匯出指派不得有修飾詞。", + "An_export_assignment_cannot_have_modifiers_1120": "匯出指派不得有修飾元。", "An_export_declaration_can_only_be_used_in_a_module_1233": "匯出宣告只可用於模組中。", - "An_export_declaration_cannot_have_modifiers_1193": "匯出宣告不得有修飾詞。", + "An_export_declaration_cannot_have_modifiers_1193": "匯出宣告不得有修飾元。", "An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive_1198": "擴充的 Unicode 逸出值必須介於 0x0 與 0x10FFFF (不含) 之間。", "An_implementation_cannot_be_declared_in_ambient_contexts_1183": "不得在環境內容中宣告實作。", "An_import_declaration_can_only_be_used_in_a_namespace_or_module_1232": "匯入宣告只可用於命名空間或模組中。", - "An_import_declaration_cannot_have_modifiers_1191": "匯入宣告不得有修飾詞。", + "An_import_declaration_cannot_have_modifiers_1191": "匯入宣告不得有修飾元。", "An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead_2691": "匯入路徑的結尾不得為 '{0}' 副檔名。請考慮改為匯入 '{1}'。", "An_index_expression_argument_must_be_of_type_string_number_symbol_or_any_2342": "索引運算式引數必須是 'string'、'number'、'symbol' 或 'any' 類型。", "An_index_signature_cannot_have_a_rest_parameter_1017": "索引簽章不得有剩餘參數。", "An_index_signature_must_have_a_type_annotation_1021": "索引簽章必須有類型註釋。", "An_index_signature_must_have_exactly_one_parameter_1096": "索引簽章只可有一個參數。", "An_index_signature_parameter_cannot_have_a_question_mark_1019": "索引簽章參數不得有問號。", - "An_index_signature_parameter_cannot_have_an_accessibility_modifier_1018": "索引簽章參數不得有存取範圍修飾詞。", + "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}'。", @@ -183,7 +183,7 @@ "Array_element_destructuring_pattern_expected_1181": "必須是陣列項目解構模式。", "Asterisk_Slash_expected_1010": "必須是 '*/'。", "Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_2669": "全域範圍的增強指定只能在外部模組宣告或環境模組宣告直接巢狀。", - "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "除非全域範圍的增強指定已顯示在環境內容中,否則應含有 'declare' 修飾詞。", + "Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambien_2670": "除非全域範圍的增強指定已顯示在環境內容中,否則應含有 'declare' 修飾元。", "Auto_discovery_for_typings_is_enabled_in_project_0_Running_extra_resolution_pass_for_module_1_using__6140": "專案 '{0}' 中已啟用鍵入的自動探索。正在使用快取位置 '{2}' 執行模組 '{1}' 的額外解析傳遞。", "Base_class_expressions_cannot_reference_class_type_parameters_2562": "基底類別運算式無法參考類別型別參數。", "Base_constructor_return_type_0_is_not_a_class_or_interface_type_2509": "基底建構函式傳回型別 '{0}' 不是類別或介面類型。", @@ -441,7 +441,7 @@ "Function_implementation_is_missing_or_not_immediately_following_the_declaration_2391": "遺漏函式實作,或函式實作未緊接在宣告之後。", "Function_implementation_name_must_be_0_2389": "函式實作名稱必須是 '{0}'。", "Function_implicitly_has_return_type_any_because_it_does_not_have_a_return_type_annotation_and_is_ref_7024": "函式因為沒有傳回型別註解,並在其中一個傳回運算式中直接或間接參考了自己,所以隱含了傳回型別 'any'。", - "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函式缺少結束傳回陳述式,且傳回類型不包括 'undefined'。", + "Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined_2366": "函式缺少結束 return 陳述式,且傳回類型不包括 'undefined'。", "Function_overload_must_be_static_2387": "函式多載必須為靜態。", "Function_overload_must_not_be_static_2388": "函式多載不可為靜態。", "Generate_get_and_set_accessors_95046": "產生 'get' 與 'set' 存取子", @@ -565,7 +565,7 @@ "Method_0_cannot_have_an_implementation_because_it_is_marked_abstract_1245": "因為方法 '{0}' 已標記為抽象,所以不可具有實作。", "Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2_4101": "匯出介面的方法 '{0}' 具有或使用私用模組 '{2}' 的名稱 '{1}'。", "Method_0_of_exported_interface_has_or_is_using_private_name_1_4102": "匯出介面的方法 '{0}' 具有或使用私用名稱 '{1}'。", - "Modifiers_cannot_appear_here_1184": "此處不得出現修飾詞。", + "Modifiers_cannot_appear_here_1184": "此處不得出現修飾元。", "Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_1340": "模組 '{0}' 未參考任何類型,但在此用為類型。", "Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here_1339": "模組 '{0}' 未參考任何值,但在此用為值。", "Module_0_has_already_exported_a_member_named_1_Consider_explicitly_re_exporting_to_resolve_the_ambig_2308": "模組 {0} 已匯出名為 '{1}' 的成員。請考慮明確重新匯出項目以解決模稜兩可的情形。", @@ -1009,26 +1009,26 @@ "_0_is_referenced_directly_or_indirectly_in_its_own_base_expression_2506": "'{0}' 在其本身的基底運算式中直接或間接受到參考。", "_0_is_referenced_directly_or_indirectly_in_its_own_type_annotation_2502": "'{0}' 在其本身的類型註釋中直接或間接受到參考。", "_0_list_cannot_be_empty_1097": "'{0}' 清單不得為空白。", - "_0_modifier_already_seen_1030": "已有 '{0}' 修飾詞。", - "_0_modifier_cannot_appear_on_a_class_element_1031": "類別項目不得有 '{0}' 修飾詞。", - "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "建構函式宣告不得有 '{0}' 修飾詞。", - "_0_modifier_cannot_appear_on_a_data_property_1043": "資料屬性不得有 '{0}' 修飾詞。", - "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "模組或命名空間元素不能有 '{0}' 修飾詞。", - "_0_modifier_cannot_appear_on_a_parameter_1090": "參數不得有 '{0}' 修飾詞。", - "_0_modifier_cannot_appear_on_a_type_member_1070": "類型成員不能有 '{0}' 修飾詞。", - "_0_modifier_cannot_appear_on_an_index_signature_1071": "索引簽章不能有 '{0}' 修飾詞。", - "_0_modifier_cannot_be_used_here_1042": "無法在此處使用 '{0}' 修飾詞。", - "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "無法在環境內容中使用 '{0}' 修飾詞。", - "_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 修飾詞無法與 '{1}' 修飾詞並用。", - "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' 修飾詞無法與類別宣告並用。", - "_0_modifier_must_precede_1_modifier_1029": "'{0}' 修飾詞必須在 '{1}' 修飾詞之前。", + "_0_modifier_already_seen_1030": "已有 '{0}' 修飾元。", + "_0_modifier_cannot_appear_on_a_class_element_1031": "類別項目不得有 '{0}' 修飾元。", + "_0_modifier_cannot_appear_on_a_constructor_declaration_1089": "建構函式宣告不得有 '{0}' 修飾元。", + "_0_modifier_cannot_appear_on_a_data_property_1043": "資料屬性不得有 '{0}' 修飾元。", + "_0_modifier_cannot_appear_on_a_module_or_namespace_element_1044": "模組或命名空間元素不能有 '{0}' 修飾元。", + "_0_modifier_cannot_appear_on_a_parameter_1090": "參數不得有 '{0}' 修飾元。", + "_0_modifier_cannot_appear_on_a_type_member_1070": "類型成員不能有 '{0}' 修飾元。", + "_0_modifier_cannot_appear_on_an_index_signature_1071": "索引簽章不能有 '{0}' 修飾元。", + "_0_modifier_cannot_be_used_here_1042": "無法在此處使用 '{0}' 修飾元。", + "_0_modifier_cannot_be_used_in_an_ambient_context_1040": "無法在環境內容中使用 '{0}' 修飾元。", + "_0_modifier_cannot_be_used_with_1_modifier_1243": "'{0}' 修飾元無法與 '{1}' 修飾元並用。", + "_0_modifier_cannot_be_used_with_a_class_declaration_1041": "'{0}' 修飾元無法與類別宣告並用。", + "_0_modifier_must_precede_1_modifier_1029": "'{0}' 修飾元必須在 '{1}' 修飾元之前。", "_0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here_2702": "'{0}' 只參考類型,但在這裡用作命名空間。", "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_2693": "'{0}' 只會參考類型,但此處將其用為值。", "_0_refers_to_a_UMD_global_but_the_current_file_is_a_module_Consider_adding_an_import_instead_2686": "'{0}' 指的是全域的 UMD,但目前的檔案為模組。請考慮改為新增匯入。", "_0_tag_already_specified_1223": "已指定 '{0}' 標記。", "_0_tag_cannot_be_used_independently_as_a_top_level_JSDoc_tag_1253": "'{0}' 標記不得獨立用作頂層 JSDoc 標記。", "_0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type_7010": "缺少傳回型別註解的 '{0}' 隱含了 '{1}' 傳回型別。", - "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 修飾詞只能出現在類別宣告、方法宣告或屬性宣告。", + "abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration_1242": "'abstract' 修飾元只能出現在類別宣告、方法宣告或屬性宣告。", "await_expression_is_only_allowed_within_an_async_function_1308": "只有非同步函式才允許 'await' 運算式。", "await_expressions_cannot_be_used_in_a_parameter_initializer_2524": "'await' 運算式不得用於參數初始設定式。", "baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1_6106": "'baseUrl' 選項已設為 '{0}'。此值將用於解析非相對的模組名稱 '{1}'。", @@ -1044,7 +1044,7 @@ "delete_this_Project_0_is_up_to_date_because_it_was_previously_built_6360": "刪除此項目 - 因為先前已建置專案 '{0}',所以其為最新狀態", "enum_declarations_can_only_be_used_in_a_ts_file_8015": "「列舉宣告」只可用於 .ts 檔案中。", "export_can_only_be_used_in_a_ts_file_8003": "'export=' 只可用於 .ts 檔案中。", - "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' 修飾詞無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。", + "export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always__2668": "'export' 修飾元無法套用至環境模組或模組增強指定,原因是這二者永遠會顯示。", "extends_clause_already_seen_1172": "已經有 'extends' 子句。", "extends_clause_must_precede_implements_clause_1173": "'extends' 子句必須在 'implements' 子句之前。", "extends_clause_of_exported_class_0_has_or_is_using_private_name_1_4020": "匯出類別 '{0}' 的 'extends' 子句具有或使用私用名稱 '{1}'。", @@ -1069,7 +1069,7 @@ "package_json_has_0_field_1_that_references_2_6101": "'package.json' 有參考 '{2}' 的 '{0}' 欄位 '{1}'。", "parameter_modifiers_can_only_be_used_in_a_ts_file_8012": "'parameter modifiers' 只可用於 .ts 檔案中。", "paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0_6091": "'paths' 選項已指定,將尋找符合模組名稱 '{0}' 的模式。", - "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾詞只能出現在屬性宣告或索引簽章。", + "readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature_1024": "'readonly' 修飾元只能出現在屬性宣告或索引簽章。", "require_call_may_be_converted_to_an_import_80005": "'require' 呼叫可能會轉換為匯入。", "rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0_6107": "'rootDirs' 選項已設定。該選項將用於解析相對的模組名稱 '{0}'。", "super_can_only_be_referenced_in_a_derived_class_2335": "只有衍生類別中才可參考 'super'。", diff --git a/package.json b/package.json index 35293854a4b..bbd2fd723b2 100644 --- a/package.json +++ b/package.json @@ -54,9 +54,9 @@ "@types/through2": "latest", "@types/travis-fold": "latest", "@types/xml2js": "^0.4.0", - "@typescript-eslint/eslint-plugin": "2.2.0", - "@typescript-eslint/experimental-utils": "2.2.0", - "@typescript-eslint/parser": "2.2.0", + "@typescript-eslint/eslint-plugin": "2.3.2", + "@typescript-eslint/experimental-utils": "2.3.2", + "@typescript-eslint/parser": "2.3.2", "async": "latest", "azure-devops-node-api": "^8.0.0", "browser-resolve": "^1.11.2", @@ -65,10 +65,10 @@ "chalk": "latest", "convert-source-map": "latest", "del": "5.1.0", - "eslint": "6.3.0", + "eslint": "6.5.1", "eslint-formatter-autolinkable-stylish": "1.0.3", "eslint-plugin-import": "2.18.2", - "eslint-plugin-jsdoc": "15.9.1", + "eslint-plugin-jsdoc": "15.9.9", "eslint-plugin-no-null": "1.0.2", "fancy-log": "latest", "fs-extra": "^6.0.1", diff --git a/src/compiler/binder.ts b/src/compiler/binder.ts index 6bd6045a551..e1fdfc258e0 100644 --- a/src/compiler/binder.ts +++ b/src/compiler/binder.ts @@ -161,7 +161,12 @@ namespace ts { IsObjectLiteralOrClassExpressionMethod = 1 << 7, } - let flowNodeCreated: (node: T) => T = identity; + function initFlowNode(node: T) { + Debug.attachFlowNodeDebugInfo(node); + return node; + } + + let flowNodeCreated: (node: T) => T = initFlowNode; const binder = createBinder(); @@ -238,6 +243,10 @@ namespace ts { Symbol = objectAllocator.getSymbolConstructor(); + // Attach debugging information if necessary + Debug.attachFlowNodeDebugInfo(unreachableFlow); + Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow); + if (!file.locals) { bind(file); file.symbolCount = symbolCount; @@ -626,7 +635,7 @@ namespace ts { // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave // similarly to break statements that exit to a label just past the statement body. if (!isIIFE) { - currentFlow = { flags: FlowFlags.Start }; + currentFlow = initFlowNode({ flags: FlowFlags.Start }); if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) { currentFlow.node = node; } @@ -638,7 +647,7 @@ namespace ts { currentContinueTarget = undefined; activeLabels = undefined; hasExplicitReturn = false; - flowNodeCreated = identity; + flowNodeCreated = initFlowNode; bindChildren(node); // Reset all reachability check related flags on node (for incremental scenarios) node.flags &= ~NodeFlags.ReachabilityAndEmitFlags; @@ -812,9 +821,6 @@ namespace ts { case SyntaxKind.JSDocEnumTag: bindJSDocTypeAlias(node as JSDocTypedefTag | JSDocCallbackTag | JSDocEnumTag); break; - case SyntaxKind.JSDocClassTag: - bindJSDocClassTag(node as JSDocClassTag); - break; // In source files and blocks, bind functions first to match hoisting that occurs at runtime case SyntaxKind.SourceFile: { bindEachFunctionsFirst((node as SourceFile).statements); @@ -856,9 +862,8 @@ namespace ts { function isNarrowableReference(expr: Expression): boolean { return expr.kind === SyntaxKind.Identifier || expr.kind === SyntaxKind.ThisKeyword || expr.kind === SyntaxKind.SuperKeyword || (isPropertyAccessExpression(expr) || isNonNullExpression(expr) || isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) || - isElementAccessExpression(expr) && - isStringOrNumericLiteralLike(expr.argumentExpression) && - isNarrowableReference(expr.expression); + isElementAccessExpression(expr) && isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) || + isOptionalChain(expr); } function hasNarrowableArgument(expr: CallExpression) { @@ -920,11 +925,11 @@ namespace ts { } function createBranchLabel(): FlowLabel { - return { flags: FlowFlags.BranchLabel, antecedents: undefined }; + return initFlowNode({ flags: FlowFlags.BranchLabel, antecedents: undefined }); } function createLoopLabel(): FlowLabel { - return { flags: FlowFlags.LoopLabel, antecedents: undefined }; + return initFlowNode({ flags: FlowFlags.LoopLabel, antecedents: undefined }); } function setFlowNodeReferenced(flow: FlowNode) { @@ -948,7 +953,7 @@ namespace ts { } if (expression.kind === SyntaxKind.TrueKeyword && flags & FlowFlags.FalseCondition || expression.kind === SyntaxKind.FalseKeyword && flags & FlowFlags.TrueCondition) { - if (!isOptionalChainRoot(expression.parent)) { + if (!isExpressionOfOptionalChainRoot(expression)) { return unreachableFlow; } } @@ -1194,7 +1199,7 @@ namespace ts { // as possible antecedents of the start of the `catch` or `finally` blocks. // Don't bother intercepting the call if there's no finally or catch block that needs the information if (node.catchClause || node.finallyBlock) { - flowNodeCreated = node => (tryPriors.push(node), node); + flowNodeCreated = node => (tryPriors.push(node), initFlowNode(node)); } bind(node.tryBlock); flowNodeCreated = oldFlowNodeCreated; @@ -1263,7 +1268,7 @@ namespace ts { // // extra edges that we inject allows to control this behavior // if when walking the flow we step on post-finally edge - we can mark matching pre-finally edge as locked so it will be skipped. - const preFinallyFlow: PreFinallyFlow = { flags: FlowFlags.PreFinally, antecedent: preFinallyPrior, lock: {} }; + const preFinallyFlow: PreFinallyFlow = initFlowNode({ flags: FlowFlags.PreFinally, antecedent: preFinallyPrior, lock: {} }); addAntecedent(preFinallyLabel, preFinallyFlow); currentFlow = finishFlowLabel(preFinallyLabel); @@ -1333,7 +1338,7 @@ namespace ts { bind(clause); fallthroughFlow = currentFlow; if (!(currentFlow.flags & FlowFlags.Unreachable) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) { - errorOnFirstToken(clause, Diagnostics.Fallthrough_case_in_switch); + clause.fallthroughFlowNode = currentFlow; } } clauses.transformFlags = subtreeTransformFlags | TransformFlags.HasComputedFlags; @@ -1984,7 +1989,7 @@ namespace ts { const host = getJSDocHost(typeAlias); container = findAncestor(host.parent, n => !!(getContainerFlags(n) & ContainerFlags.IsContainer)) || file; blockScopeContainer = getEnclosingBlockScopeContainer(host) || file; - currentFlow = { flags: FlowFlags.Start }; + currentFlow = initFlowNode({ flags: FlowFlags.Start }); parent = typeAlias; bind(typeAlias.typeExpression); const declName = getNameOfDeclaration(typeAlias); @@ -2446,6 +2451,8 @@ namespace ts { case SyntaxKind.JSDocTypeLiteral: case SyntaxKind.MappedType: return bindAnonymousTypeWorker(node as TypeLiteralNode | MappedTypeNode | JSDocTypeLiteral); + case SyntaxKind.JSDocClassTag: + return bindJSDocClassTag(node as JSDocClassTag); case SyntaxKind.ObjectLiteralExpression: return bindObjectLiteralExpression(node); case SyntaxKind.FunctionExpression: @@ -2683,7 +2690,8 @@ namespace ts { const flags = exportAssignmentIsAlias(node) ? SymbolFlags.Alias // An export= with an EntityNameExpression or a ClassExpression exports all meanings of that identifier or class : SymbolFlags.Property | SymbolFlags.ExportValue | SymbolFlags.ValueModule; - declareSymbol(file.symbol.exports!, file.symbol, node, flags | SymbolFlags.Assignment, SymbolFlags.None); + const symbol = declareSymbol(file.symbol.exports!, file.symbol, node, flags | SymbolFlags.Assignment, SymbolFlags.None); + setValueDeclaration(symbol, node); } function bindThisPropertyAssignment(node: BindablePropertyAssignmentExpression | PropertyAccessExpression | LiteralLikeElementAccessExpression) { @@ -2781,6 +2789,10 @@ namespace ts { function bindObjectDefinePrototypeProperty(node: BindableObjectDefinePropertyCall) { const namespaceSymbol = lookupSymbolForPropertyAccess((node.arguments[0] as PropertyAccessExpression).expression as EntityNameExpression); + if (namespaceSymbol) { + // Ensure the namespace symbol becomes class-like + addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, SymbolFlags.Class); + } bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true); } @@ -2862,7 +2874,7 @@ namespace ts { } }); } - if (containerIsClass && namespaceSymbol) { + if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) { addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, SymbolFlags.Class); } return namespaceSymbol; diff --git a/src/compiler/builder.ts b/src/compiler/builder.ts index 7451eb678b4..dc3b108b983 100644 --- a/src/compiler/builder.ts +++ b/src/compiler/builder.ts @@ -251,6 +251,7 @@ namespace ts { state.seenAffectedFiles = createMap(); } + state.emittedBuildInfo = !state.changedFilesSet.size && !state.affectedFilesPendingEmit; return state; } @@ -1118,7 +1119,7 @@ namespace ts { const state: ReusableBuilderProgramState = { fileInfos, - compilerOptions: convertFromReusableCompilerOptions(program.options, toAbsolutePath), + compilerOptions: convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath), referencedMap: getMapOfReferencedSet(program.referencedMap, toPath), exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath), semanticDiagnosticsPerFile: program.semanticDiagnosticsPerFile && arrayToMap(program.semanticDiagnosticsPerFile, value => toPath(isString(value) ? value : value[0]), value => isString(value) ? emptyArray : value[1]), @@ -1156,40 +1157,6 @@ namespace ts { } } - function convertFromReusableCompilerOptions(options: CompilerOptions, toAbsolutePath: (path: string) => string) { - const result: CompilerOptions = {}; - const optionsNameMap = getOptionNameMap().optionNameMap; - - for (const name in options) { - if (hasProperty(options, name)) { - result[name] = convertFromReusableCompilerOptionValue( - optionsNameMap.get(name.toLowerCase()), - options[name] as CompilerOptionsValue, - toAbsolutePath - ); - } - } - if (result.configFilePath) { - result.configFilePath = toAbsolutePath(result.configFilePath); - } - return result; - } - - function convertFromReusableCompilerOptionValue(option: CommandLineOption | undefined, value: CompilerOptionsValue, toAbsolutePath: (path: string) => string) { - if (option) { - if (option.type === "list") { - const values = value as readonly (string | number)[]; - if (option.element.isFilePath && values.length) { - return values.map(toAbsolutePath); - } - } - else if (option.isFilePath) { - return toAbsolutePath(value as string); - } - } - return value; - } - export function createRedirectedBuilderProgram(state: { program: Program | undefined; compilerOptions: CompilerOptions; }, configFileParsingDiagnostics: readonly Diagnostic[]): BuilderProgram { return { getState: notImplemented, diff --git a/src/compiler/checker.ts b/src/compiler/checker.ts index 845c145fb6a..647a5e8f57b 100644 --- a/src/compiler/checker.ts +++ b/src/compiler/checker.ts @@ -174,12 +174,6 @@ namespace ts { IsForSignatureHelp = 1 << 4, // Call resolution for purposes of signature help } - const enum ContextFlags { - None = 0, - Signature = 1 << 0, // Obtaining contextual signature - NoConstraints = 1 << 1, // Don't obtain type variable constraints - } - const enum AccessFlags { None = 0, NoIndexSignatures = 1 << 0, @@ -333,10 +327,6 @@ namespace ts { /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */ let apparentArgumentCount: number | undefined; - // This object is reused for `checkOptionalExpression` return values to avoid frequent GC due to nursery object allocations. - // This object represents a pool-size of 1. - const pooledOptionalTypeResult: { isOptional: boolean, type: Type } = { isOptional: false, type: undefined! }; - // for public members that accept a Node or one of its subtypes, we must guard against // synthetic nodes created during transformations by calling `getParseTreeNode`. // for most of these, we perform the guard only on `checker` to avoid any possible @@ -454,9 +444,9 @@ namespace ts { }, getAugmentedPropertiesOfType, getRootSymbols, - getContextualType: nodeIn => { + getContextualType: (nodeIn: Expression, contextFlags?: ContextFlags) => { const node = getParseTreeNode(nodeIn, isExpression); - return node ? getContextualType(node) : undefined; + return node ? getContextualType(node, contextFlags) : undefined; }, getContextualTypeForObjectLiteralElement: nodeIn => { const node = getParseTreeNode(nodeIn, isObjectLiteralElementLike); @@ -718,10 +708,10 @@ namespace ts { const noTypePredicate = createTypePredicate(TypePredicateKind.Identifier, "<>", 0, anyType); - const anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - const resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); - const silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + const anySignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, SignatureFlags.None); + const unknownSignature = createSignature(undefined, undefined, undefined, emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, SignatureFlags.None); + const resolvingSignature = createSignature(undefined, undefined, undefined, emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, SignatureFlags.None); + const silentNeverSignature = createSignature(undefined, undefined, undefined, emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, SignatureFlags.None); const enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true); @@ -2202,7 +2192,18 @@ namespace ts { )); } else { - error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + if (moduleSymbol.exports && moduleSymbol.exports.has(node.symbol.escapedName)) { + error( + node.name, + Diagnostics.Module_0_has_no_default_export_Did_you_mean_to_use_import_1_from_0_instead, + symbolToString(moduleSymbol), + symbolToString(node.symbol), + ); + } + else { + error(node.name, Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol)); + } + } } else if (hasSyntheticDefault) { @@ -2310,7 +2311,17 @@ namespace ts { } } else { - error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + if (moduleSymbol.exports && moduleSymbol.exports.has(InternalSymbolName.Default)) { + error( + name, + Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, + moduleName, + declarationName + ); + } + else { + error(name, Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName); + } } } return symbol; @@ -5329,7 +5340,7 @@ namespace ts { // so we don't even have placeholders to fill in. if (length(realMembers)) { const localName = getInternalSymbolName(symbol, symbolName); - serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, /*suppressNewPrivateContext*/ false); + serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & SymbolFlags.Function)); } if (length(mergedMembers)) { const localName = getInternalSymbolName(symbol, symbolName); @@ -5572,7 +5583,10 @@ namespace ts { /*decorators*/ undefined, /*modifiers*/ undefined, createImportClause(createIdentifier(localName), /*namedBindings*/ undefined), - createLiteral(getSpecifierForModuleSymbol(target.parent!, context)) + // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned + // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag + // In such cases, the `target` refers to the module itself already + createLiteral(getSpecifierForModuleSymbol(target.parent || target, context)) ), ModifierFlags.None); break; case SyntaxKind.NamespaceImport: @@ -5593,7 +5607,7 @@ namespace ts { createIdentifier(localName) ) ])), - createLiteral(getSpecifierForModuleSymbol(target.parent!, context)) + createLiteral(getSpecifierForModuleSymbol(target.parent || target, context)) ), ModifierFlags.None); break; case SyntaxKind.ExportSpecifier: @@ -7252,7 +7266,7 @@ namespace ts { // Handle variable, parameter or property if (!pushTypeResolution(symbol, TypeSystemPropertyName.Type)) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & SymbolFlags.ValueModule) { + if (symbol.flags & SymbolFlags.ValueModule && !(symbol.flags & SymbolFlags.Assignment)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -7322,7 +7336,7 @@ namespace ts { if (!popTypeResolution()) { // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty` - if (symbol.flags & SymbolFlags.ValueModule) { + if (symbol.flags & SymbolFlags.ValueModule && !(symbol.flags & SymbolFlags.Assignment)) { return getTypeOfFuncClassEnumModule(symbol); } return reportCircularityError(symbol); @@ -7415,7 +7429,9 @@ namespace ts { } else { Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function"); - errorOrSuggestion(noImplicitAny, getter!, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + if (!isPrivateWithinAmbient(getter!)) { + errorOrSuggestion(noImplicitAny, getter!, Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol)); + } } return anyType; } @@ -7668,6 +7684,7 @@ namespace ts { // The outer type parameters are those defined by enclosing generic classes, methods, or functions. function getOuterTypeParametersOfClassOrInterface(symbol: Symbol): TypeParameter[] | undefined { const declaration = symbol.flags & SymbolFlags.Class ? symbol.valueDeclaration : getDeclarationOfKind(symbol, SyntaxKind.InterfaceDeclaration)!; + Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations"); return getOuterTypeParameters(declaration); } @@ -7700,7 +7717,7 @@ namespace ts { const signatures = getSignaturesOfType(type, SignatureKind.Construct); if (signatures.length === 1) { const s = signatures[0]; - return !s.typeParameters && s.parameters.length === 1 && s.hasRestParameter && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; + return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType; } return false; } @@ -8591,10 +8608,9 @@ namespace ts { resolvedReturnType: Type | undefined, resolvedTypePredicate: TypePredicate | undefined, minArgumentCount: number, - hasRestParameter: boolean, - hasLiteralTypes: boolean, + flags: SignatureFlags ): Signature { - const sig = new Signature(checker); + const sig = new Signature(checker, flags); sig.declaration = declaration; sig.typeParameters = typeParameters; sig.parameters = parameters; @@ -8602,8 +8618,6 @@ namespace ts { sig.resolvedReturnType = resolvedReturnType; sig.resolvedTypePredicate = resolvedTypePredicate; sig.minArgumentCount = minArgumentCount; - sig.hasRestParameter = hasRestParameter; - sig.hasLiteralTypes = hasLiteralTypes; sig.target = undefined; sig.mapper = undefined; return sig; @@ -8611,7 +8625,7 @@ namespace ts { function cloneSignature(sig: Signature): Signature { const result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, - /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes); + /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & SignatureFlags.PropagatingFlags); result.target = sig.target; result.mapper = sig.mapper; return result; @@ -8625,14 +8639,19 @@ namespace ts { return result; } + function getOptionalCallSignature(signature: Signature) { + return signatureIsOptionalCall(signature) ? signature : + (signature.optionalCallSignatureCache || (signature.optionalCallSignatureCache = createOptionalCallSignature(signature))); + } + function createOptionalCallSignature(signature: Signature) { const result = cloneSignature(signature); - result.isOptionalCall = true; + result.flags |= SignatureFlags.IsOptionalCall; return result; } function getExpandedParameters(sig: Signature): readonly Symbol[] { - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { const restIndex = sig.parameters.length - 1; const restParameter = sig.parameters[restIndex]; const restType = getTypeOfSymbol(restParameter); @@ -8658,7 +8677,7 @@ namespace ts { const baseConstructorType = getBaseConstructorTypeOfClass(classType); const baseSignatures = getSignaturesOfType(baseConstructorType, SignatureKind.Construct); if (baseSignatures.length === 0) { - return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false)]; + return [createSignature(undefined, classType.localTypeParameters, undefined, emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, SignatureFlags.None)]; } const baseTypeNode = getBaseTypeNodeOfClass(classType)!; const isJavaScript = isInJSFile(baseTypeNode); @@ -8822,8 +8841,6 @@ namespace ts { const params = combineUnionParameters(left, right); const thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter); const minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount); - const hasRestParam = left.hasRestParameter || right.hasRestParameter; - const hasLiteralTypes = left.hasLiteralTypes || right.hasLiteralTypes; const result = createSignature( declaration, left.typeParameters || right.typeParameters, @@ -8832,8 +8849,7 @@ namespace ts { /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgCount, - hasRestParam, - hasLiteralTypes + (left.flags | right.flags) & SignatureFlags.PropagatingFlags ); result.unionSignatures = concatenate(left.unionSignatures || [left], [right]); return result; @@ -9015,7 +9031,7 @@ namespace ts { constructSignatures = addRange(constructSignatures.slice(), mapDefined( type.callSignatures, sig => isJSConstructor(sig.declaration) ? - createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.hasRestParameter, sig.hasLiteralTypes) : + createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & SignatureFlags.PropagatingFlags) : undefined)); } if (!constructSignatures.length) { @@ -10022,7 +10038,7 @@ namespace ts { const links = getNodeLinks(declaration); if (!links.resolvedSignature) { const parameters: Symbol[] = []; - let hasLiteralTypes = false; + let flags = SignatureFlags.None; let minArgumentCount = 0; let thisParameter: Symbol | undefined; let hasThisParameter = false; @@ -10056,7 +10072,7 @@ namespace ts { } if (type && type.kind === SyntaxKind.LiteralType) { - hasLiteralTypes = true; + flags |= SignatureFlags.HasLiteralTypes; } // Record a new minimum argument count if this is not an optional parameter @@ -10085,10 +10101,12 @@ namespace ts { getDeclaredTypeOfClassOrInterface(getMergedSymbol((declaration.parent).symbol)) : undefined; const typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration); - const hasRestLikeParameter = hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters); + if (hasRestParameter(declaration) || isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) { + flags |= SignatureFlags.HasRestParameter; + } links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, - minArgumentCount, hasRestLikeParameter, hasLiteralTypes); + minArgumentCount, flags); } return links.resolvedSignature; } @@ -10243,8 +10261,8 @@ namespace ts { signature.unionSignatures ? getUnionType(map(signature.unionSignatures, getReturnTypeOfSignature), UnionReduction.Subtype) : getReturnTypeFromAnnotation(signature.declaration!) || (nodeIsMissing((signature.declaration).body) ? anyType : getReturnTypeFromBody(signature.declaration)); - if (signature.isOptionalCall) { - type = propagateOptionalTypeMarker(type, /*wasOptional*/ true); + if (signatureIsOptionalCall(signature)) { + type = addOptionalTypeMarker(type); } if (!popTypeResolution()) { if (signature.declaration) { @@ -10304,7 +10322,7 @@ namespace ts { } function tryGetRestTypeOfSignature(signature: Signature): Type | undefined { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { const sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); const restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType; return restType && getIndexTypeOfType(restType, IndexKind.Number); @@ -10720,7 +10738,7 @@ namespace ts { errorType; } if (symbol.flags & SymbolFlags.Value && isJSDocTypeReference(node)) { - const jsdocType = getTypeFromJSAlias(node, symbol); + const jsdocType = getTypeFromJSDocValueReference(node, symbol); if (jsdocType) { return jsdocType; } @@ -10734,19 +10752,25 @@ namespace ts { } /** - * A JSdoc TypeReference may be to a value imported from commonjs. - * These should really be aliases, but this special-case code fakes alias resolution - * by producing a type from a value. + * A JSdoc TypeReference may be to a value, but resolve it as a type anyway. + * Note: If the value is imported from commonjs, it should really be an alias, + * but this function fakes special-case code fakes alias resolution as well. */ - function getTypeFromJSAlias(node: NodeWithTypeArguments, symbol: Symbol): Type | undefined { + function getTypeFromJSDocValueReference(node: NodeWithTypeArguments, symbol: Symbol): Type | undefined { const valueType = getTypeOfSymbol(symbol); - const typeType = - valueType.symbol && - valueType.symbol !== symbol && // Make sure this is a commonjs export by checking that symbol -> type -> symbol doesn't roundtrip. - getTypeReferenceType(node, valueType.symbol); - if (typeType) { - return getSymbolLinks(symbol).resolvedJSDocType = typeType; + let typeType = valueType; + if (symbol.valueDeclaration) { + const decl = getRootDeclaration(symbol.valueDeclaration); + const isRequireAlias = isVariableDeclaration(decl) + && decl.initializer + && isCallExpression(decl.initializer) + && isRequireCall(decl.initializer, /*requireStringLiteralLikeArgument*/ true) + && valueType.symbol; + if (isRequireAlias) { + typeType = getTypeReferenceType(node, valueType.symbol); + } } + return getSymbolLinks(symbol).resolvedJSDocType = typeType; } function getSubstitutionType(typeVariable: TypeVariable, substitute: Type) { @@ -12412,7 +12436,7 @@ namespace ts { function getAliasSymbolForTypeNode(node: TypeNode) { let host = node.parent; - while (isParenthesizedTypeNode(host)) { + while (isParenthesizedTypeNode(host) || isTypeOperatorNode(host) && host.operator === SyntaxKind.ReadonlyKeyword) { host = host.parent; } return isTypeAlias(host) ? getSymbolOfNode(host) : undefined; @@ -12880,8 +12904,7 @@ namespace ts { /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, - signature.hasRestParameter, - signature.hasLiteralTypes); + signature.flags & SignatureFlags.PropagatingFlags); result.target = signature; result.mapper = mapper; return result; @@ -13834,7 +13857,7 @@ namespace ts { */ function isAnySignature(s: Signature) { return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 && - s.hasRestParameter && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && + signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) && isTypeAny(getReturnTypeOfSignature(s)); } @@ -16659,48 +16682,22 @@ namespace ts { return strictNullChecks ? getUnionType([type, optionalType]) : type; } + function isNotOptionalTypeMarker(type: Type) { + return type !== optionalType; + } + function removeOptionalTypeMarker(type: Type): Type { - return strictNullChecks ? filterType(type, t => t !== optionalType) : type; + return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type; } function propagateOptionalTypeMarker(type: Type, wasOptional: boolean) { return wasOptional ? addOptionalTypeMarker(type) : type; } - function createPooledOptionalTypeResult(isOptional: boolean, type: Type) { - pooledOptionalTypeResult.isOptional = isOptional; - pooledOptionalTypeResult.type = type; - return pooledOptionalTypeResult; - } - - function checkOptionalExpression( - parent: PropertyAccessExpression | QualifiedName | ElementAccessExpression | CallExpression, - expression: Expression | QualifiedName, - nullDiagnostic?: DiagnosticMessage, - undefinedDiagnostic?: DiagnosticMessage, - nullOrUndefinedDiagnostic?: DiagnosticMessage, - ) { - let isOptional = false; - let type = checkExpression(expression); - if (isOptionalChain(parent)) { - if (parent.questionDotToken) { - // If we have a questionDotToken then we are an OptionalExpression and should remove `null` and - // `undefined` from the type and add the optionalType to the result, if needed. - isOptional = isNullableType(type); - return createPooledOptionalTypeResult(isOptional, isOptional ? getNonNullableType(type) : type); - } - - // If we do not have a questionDotToken, then we are an OptionalChain and we remove the optionalType and - // indicate whether we need to add optionalType back into the result. - const nonOptionalType = removeOptionalTypeMarker(type); - if (nonOptionalType !== type) { - isOptional = true; - type = nonOptionalType; - } - } - - type = checkNonNullType(type, expression, nullDiagnostic, undefinedDiagnostic, nullOrUndefinedDiagnostic); - return createPooledOptionalTypeResult(isOptional, type); + function getOptionalExpressionType(exprType: Type, expression: Expression) { + return isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) : + isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) : + exprType; } /** @@ -17357,10 +17354,7 @@ namespace ts { // inferring a type parameter constraint. Instead, make a lower priority inference from // the full source to whatever remains in the target. For example, when inferring from // string to 'string | T', make a lower priority inference of string for T. - const savePriority = priority; - priority |= InferencePriority.NakedTypeVariable; - inferFromTypes(source, target); - priority = savePriority; + inferWithPriority(source, target, InferencePriority.NakedTypeVariable); return; } source = getUnionType(sources); @@ -17462,10 +17456,7 @@ namespace ts { else if ((isLiteralType(source) || source.flags & TypeFlags.String) && target.flags & TypeFlags.Index) { const empty = createEmptyObjectTypeFromStringLiteral(source); contravariant = !contravariant; - const savePriority = priority; - priority |= InferencePriority.LiteralKeyof; - inferFromTypes(empty, (target as IndexType).type); - priority = savePriority; + inferWithPriority(empty, (target as IndexType).type, InferencePriority.LiteralKeyof); contravariant = !contravariant; } else if (source.flags & TypeFlags.IndexedAccess && target.flags & TypeFlags.IndexedAccess) { @@ -17517,6 +17508,13 @@ namespace ts { } } + function inferWithPriority(source: Type, target: Type, newPriority: InferencePriority) { + const savePriority = priority; + priority |= newPriority; + inferFromTypes(source, target); + priority = savePriority; + } + function invokeOnce(source: Type, target: Type, action: (source: Type, target: Type) => void) { const key = source.id + "," + target.id; const status = visited && visited.get(key); @@ -17584,6 +17582,18 @@ namespace ts { return undefined; } + function getSingleTypeVariableFromIntersectionTypes(types: Type[]) { + let typeVariable: Type | undefined; + for (const type of types) { + const t = type.flags & TypeFlags.Intersection && find((type).types, t => !!getInferenceInfoForType(t)); + if (!t || typeVariable && t !== typeVariable) { + return undefined; + } + typeVariable = t; + } + return typeVariable; + } + function inferToMultipleTypes(source: Type, targets: Type[], targetFlags: TypeFlags) { let typeVariableCount = 0; if (targetFlags & TypeFlags.Union) { @@ -17611,6 +17621,16 @@ namespace ts { } } } + if (typeVariableCount === 0) { + // If every target is an intersection of types containing a single naked type variable, + // make a lower priority inference to that type variable. This handles inferring from + // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T. + const intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets); + if (intersectionTypeVariable) { + inferWithPriority(source, intersectionTypeVariable, InferencePriority.NakedTypeVariable); + } + return; + } // If the target has a single naked type variable and no inference circularities were // encountered above (meaning we explored the types fully), create a union of the source // types from which no inferences have been made so far and infer from that union to the @@ -17641,14 +17661,11 @@ namespace ts { // we want to infer string for T, not Promise | string. For intersection types // we only infer to single naked type variables. if (targetFlags & TypeFlags.Intersection ? typeVariableCount === 1 : typeVariableCount > 0) { - const savePriority = priority; - priority |= InferencePriority.NakedTypeVariable; for (const t of targets) { if (getInferenceInfoForType(t)) { - inferFromTypes(source, t); + inferWithPriority(source, t, InferencePriority.NakedTypeVariable); } } - priority = savePriority; } } @@ -17669,14 +17686,13 @@ namespace ts { if (inference && !inference.isFixed) { const inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType); if (inferredType) { - const savePriority = priority; // We assign a lower priority to inferences made from types containing non-inferrable // types because we may only have a partial result (i.e. we may have failed to make // reverse inferences for some properties). - priority |= getObjectFlags(source) & ObjectFlags.NonInferrableType ? - InferencePriority.PartialHomomorphicMappedType : InferencePriority.HomomorphicMappedType; - inferFromTypes(inferredType, inference.typeParameter); - priority = savePriority; + inferWithPriority(inferredType, inference.typeParameter, + getObjectFlags(source) & ObjectFlags.NonInferrableType ? + InferencePriority.PartialHomomorphicMappedType : + InferencePriority.HomomorphicMappedType); } } return true; @@ -17684,10 +17700,7 @@ namespace ts { if (constraintType.flags & TypeFlags.TypeParameter) { // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type // parameter. First infer from 'keyof S' to K. - const savePriority = priority; - priority |= InferencePriority.MappedTypeConstraint; - inferFromTypes(getIndexType(source), constraintType); - priority = savePriority; + inferWithPriority(getIndexType(source), constraintType, InferencePriority.MappedTypeConstraint); // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X }, // where K extends keyof T, we make the same inferences as for a homomorphic mapped type // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a @@ -18103,6 +18116,16 @@ namespace ts { return false; } + function optionalChainContainsReference(source: Node, target: Node) { + while (isOptionalChain(source)) { + source = source.expression; + if (isMatchingReference(source, target)) { + return true; + } + } + return false; + } + // Return true if target is a property access xxx.yyy, source is a property access xxx.zzz, the declared // type of xxx is a union type, and yyy is a property that is possibly a discriminant. We consider a property // a possible discriminant if its type differs in the constituents of containing union type, and if every @@ -18734,9 +18757,21 @@ namespace ts { // expressions are potential type predicate function calls. In order to avoid triggering // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call // target expression of an assertion. - const funcType = node.parent.kind === SyntaxKind.ExpressionStatement ? getTypeOfDottedName(node.expression, /*diagnostic*/ undefined) : - node.expression.kind !== SyntaxKind.SuperKeyword ? checkOptionalExpression(node, node.expression).type : - undefined; + let funcType: Type | undefined; + if (node.parent.kind === SyntaxKind.ExpressionStatement) { + funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined); + } + else if (node.expression.kind !== SyntaxKind.SuperKeyword) { + if (isOptionalChain(node)) { + funcType = checkNonNullType( + getOptionalExpressionType(checkExpression(node.expression), node.expression), + node.expression + ); + } + else { + funcType = checkNonNullExpression(node.expression); + } + } const signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, SignatureKind.Call); const candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] : some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) : @@ -18751,6 +18786,14 @@ namespace ts { signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & TypeFlags.Never); } + function getTypePredicateArgument(predicate: TypePredicate, callExpression: CallExpression) { + if (predicate.kind === TypePredicateKind.Identifier || predicate.kind === TypePredicateKind.AssertsIdentifier) { + return callExpression.arguments[predicate.parameterIndex]; + } + const invokedExpression = skipParentheses(callExpression.expression); + return isAccessExpression(invokedExpression) ? skipParentheses(invokedExpression.expression) : undefined; + } + function reportFlowControlError(node: Node) { const block = findAncestor(node, isFunctionOrModuleBlock); const sourceFile = getSourceFileOfNode(node); @@ -18769,6 +18812,13 @@ namespace ts { return !(flow.flags & FlowFlags.PreFinally && (flow).lock.locked) && isReachableFlowNodeWorker(flow, /*skipCacheCheck*/ false); } + function isFalseExpression(expr: Expression): boolean { + const node = skipParentheses(expr); + return node.kind === SyntaxKind.FalseKeyword || node.kind === SyntaxKind.BinaryExpression && ( + (node).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken && (isFalseExpression((node).left) || isFalseExpression((node).right)) || + (node).operatorToken.kind === SyntaxKind.BarBarToken && isFalseExpression((node).left) && isFalseExpression((node).right)); + } + function isReachableFlowNodeWorker(flow: FlowNode, noCacheCheck: boolean): boolean { while (true) { if (flow === lastFlowNode) { @@ -18788,8 +18838,17 @@ namespace ts { } else if (flags & FlowFlags.Call) { const signature = getEffectsSignature((flow).node); - if (signature && getReturnTypeOfSignature(signature).flags & TypeFlags.Never) { - return false; + if (signature) { + const predicate = getTypePredicateOfSignature(signature); + if (predicate && predicate.kind === TypePredicateKind.AssertsIdentifier) { + const predicateArgument = (flow).node.arguments[predicate.parameterIndex]; + if (predicateArgument && isFalseExpression(predicateArgument)) { + return false; + } + } + if (getReturnTypeOfSignature(signature).flags & TypeFlags.Never) { + return false; + } } flow = (flow).antecedent; } @@ -19028,6 +19087,9 @@ namespace ts { function narrowTypeByAssertion(type: Type, expr: Expression): Type { const node = skipParentheses(expr); + if (node.kind === SyntaxKind.FalseKeyword) { + return unreachableNeverType; + } if (node.kind === SyntaxKind.BinaryExpression) { if ((node).operatorToken.kind === SyntaxKind.AmpersandAmpersandToken) { return narrowTypeByAssertion(narrowTypeByAssertion(type, (node).left), (node).right); @@ -19047,7 +19109,7 @@ namespace ts { const flowType = getTypeAtFlowNode(flow.antecedent); const type = getTypeFromFlowType(flowType); const narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) : - predicate.kind === TypePredicateKind.AssertsIdentifier ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : + predicate.kind === TypePredicateKind.AssertsIdentifier && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) : type; return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType)); } @@ -19120,20 +19182,30 @@ namespace ts { if (isMatchingReference(reference, expr)) { type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (isMatchingReferenceDiscriminant(expr, type)) { - type = narrowTypeByDiscriminant( - type, - expr as AccessExpression, - t => narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd)); - } else if (expr.kind === SyntaxKind.TypeOfExpression && isMatchingReference(reference, (expr as TypeOfExpression).expression)) { type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd); } - else if (containsMatchingReferenceDiscriminant(reference, expr)) { - type = declaredType; - } - else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { - return unreachableNeverType; + else { + if (strictNullChecks) { + if (optionalChainContainsReference(expr, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, + t => !(t.flags & (TypeFlags.Undefined | TypeFlags.Never))); + } + else if (expr.kind === SyntaxKind.TypeOfExpression && optionalChainContainsReference((expr as TypeOfExpression).expression, reference)) { + type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, + t => !(t.flags & TypeFlags.Never || t.flags & TypeFlags.StringLiteral && (t).value === "undefined")); + } + } + if (isMatchingReferenceDiscriminant(expr, type)) { + type = narrowTypeByDiscriminant(type, expr as AccessExpression, + t => narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd)); + } + else if (containsMatchingReferenceDiscriminant(reference, expr)) { + type = declaredType; + } + else if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) { + return unreachableNeverType; + } } return createFlowType(type, isIncomplete(flowType)); } @@ -19278,6 +19350,9 @@ namespace ts { if (isMatchingReference(reference, expr)) { return getTypeWithFacts(type, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) { + type = getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); + } if (isMatchingReferenceDiscriminant(expr, declaredType)) { return narrowTypeByDiscriminant(type, expr, t => getTypeWithFacts(t, assumeTrue ? TypeFacts.Truthy : TypeFacts.Falsy)); } @@ -19329,6 +19404,14 @@ namespace ts { if (isMatchingReference(reference, right)) { return narrowTypeByEquality(type, operator, left, assumeTrue); } + if (strictNullChecks) { + if (optionalChainContainsReference(left, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, right, assumeTrue); + } + else if (optionalChainContainsReference(right, reference)) { + type = narrowTypeByOptionalChainContainment(type, operator, left, assumeTrue); + } + } if (isMatchingReferenceDiscriminant(left, declaredType)) { return narrowTypeByDiscriminant(type, left, t => narrowTypeByEquality(t, operator, right, assumeTrue)); } @@ -19353,6 +19436,16 @@ namespace ts { return type; } + function narrowTypeByOptionalChainContainment(type: Type, operator: SyntaxKind, value: Expression, assumeTrue: boolean): Type { + // We are in a branch of obj?.foo === value or obj?.foo !== value. We remove undefined and null from + // the type of obj if (a) the operator is === and the type of value doesn't include undefined or (b) the + // operator is !== and the type of value is undefined. + const effectiveTrue = operator === SyntaxKind.EqualsEqualsToken || operator === SyntaxKind.EqualsEqualsEqualsToken ? assumeTrue : !assumeTrue; + const doubleEquals = operator === SyntaxKind.EqualsEqualsToken || operator === SyntaxKind.ExclamationEqualsToken; + const valueNonNullish = !(getTypeFacts(getTypeOfExpression(value)) & (doubleEquals ? TypeFacts.EQUndefinedOrNull : TypeFacts.EQUndefined)); + return effectiveTrue === valueNonNullish ? getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull) : type; + } + function narrowTypeByEquality(type: Type, operator: SyntaxKind, value: Expression, assumeTrue: boolean): Type { if (type.flags & TypeFlags.Any) { return type; @@ -19401,8 +19494,14 @@ namespace ts { function narrowTypeByTypeof(type: Type, typeOfExpr: TypeOfExpression, operator: SyntaxKind, literal: LiteralExpression, assumeTrue: boolean): Type { // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands + if (operator === SyntaxKind.ExclamationEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) { + assumeTrue = !assumeTrue; + } const target = getReferenceCandidate(typeOfExpr.expression); if (!isMatchingReference(reference, target)) { + if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) { + return getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); + } // For a reference of the form 'x.y', a 'typeof x === ...' type guard resets the // narrowed type of 'y' to its declared type. if (containsMatchingReference(reference, target)) { @@ -19410,9 +19509,6 @@ namespace ts { } return type; } - if (operator === SyntaxKind.ExclamationEqualsToken || operator === SyntaxKind.ExclamationEqualsEqualsToken) { - assumeTrue = !assumeTrue; - } if (type.flags & TypeFlags.Any && literal.text === "function") { return type; } @@ -19447,6 +19543,11 @@ namespace ts { } } + function narrowTypeBySwitchOptionalChainContainment(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number, clauseCheck: (type: Type) => boolean) { + const everyClauseChecks = clauseStart !== clauseEnd && every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck); + return everyClauseChecks ? getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull) : type; + } + function narrowTypeBySwitchOnDiscriminant(type: Type, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number) { // We only narrow if all case expressions specify // values with unit types, except for the case where @@ -19584,6 +19685,9 @@ namespace ts { function narrowTypeByInstanceof(type: Type, expr: BinaryExpression, assumeTrue: boolean): Type { const left = getReferenceCandidate(expr.left); if (!isMatchingReference(reference, left)) { + if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) { + return getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); + } // For a reference of the form 'x.y', an 'x instanceof T' type guard resets the // narrowed type of 'y' to its declared type. We do this because preceding 'x.y' // references might reference a different 'y' property. However, we make an exception @@ -19664,32 +19768,21 @@ namespace ts { function narrowTypeByTypePredicate(type: Type, predicate: TypePredicate, callExpression: CallExpression, assumeTrue: boolean): Type { // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function' - if (isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType)) { - return type; - } - if (predicate.kind === TypePredicateKind.Identifier || predicate.kind === TypePredicateKind.AssertsIdentifier) { - const predicateArgument = callExpression.arguments[predicate.parameterIndex]; - if (predicateArgument && predicate.type) { + if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) { + const predicateArgument = getTypePredicateArgument(predicate, callExpression); + if (predicateArgument) { if (isMatchingReference(reference, predicateArgument)) { return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); } + if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) && + !(getTypeFacts(predicate.type) & TypeFacts.EQUndefined)) { + return getTypeWithFacts(type, TypeFacts.NEUndefinedOrNull); + } if (containsMatchingReference(reference, predicateArgument)) { return declaredType; } } } - else { - const invokedExpression = skipParentheses(callExpression.expression); - if (isAccessExpression(invokedExpression) && predicate.type) { - const possibleReference = skipParentheses(invokedExpression.expression); - if (isMatchingReference(reference, possibleReference)) { - return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf); - } - if (containsMatchingReference(reference, possibleReference)) { - return declaredType; - } - } - } return type; } @@ -19697,7 +19790,7 @@ namespace ts { // will be a subtype or the same type as the argument. function narrowType(type: Type, expr: Expression, assumeTrue: boolean): Type { // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a` - if (isOptionalChainRoot(expr.parent) || + if (isExpressionOfOptionalChainRoot(expr) || isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === SyntaxKind.QuestionQuestionToken && expr.parent.left === expr) { return narrowTypeByOptionality(type, expr, assumeTrue); } @@ -20866,19 +20959,23 @@ namespace ts { } // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter. - function getContextualTypeForArgument(callTarget: CallLikeExpression, arg: Expression): Type | undefined { + function getContextualTypeForArgument(callTarget: CallLikeExpression, arg: Expression, contextFlags?: ContextFlags): Type | undefined { const args = getEffectiveCallArguments(callTarget); const argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression - return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex); + return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex, contextFlags); } - function getContextualTypeForArgumentAtIndex(callTarget: CallLikeExpression, argIndex: number): Type { + function getContextualTypeForArgumentAtIndex(callTarget: CallLikeExpression, argIndex: number, contextFlags?: ContextFlags): Type { // If we're already in the process of resolving the given signature, don't resolve again as // that could cause infinite recursion. Instead, return anySignature. const signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget); if (isJsxOpeningLikeElement(callTarget) && argIndex === 0) { return getEffectiveFirstArgumentForJsxSignature(signature, callTarget); } + if (contextFlags && contextFlags & ContextFlags.Completion && signature.target) { + const baseSignature = getBaseSignature(signature.target); + return intersectTypes(getTypeAtPosition(signature, argIndex), getTypeAtPosition(baseSignature, argIndex)); + } return getTypeAtPosition(signature, argIndex); } @@ -21270,7 +21367,7 @@ namespace ts { } /* falls through */ case SyntaxKind.NewExpression: - return getContextualTypeForArgument(parent, node); + return getContextualTypeForArgument(parent, node, contextFlags); case SyntaxKind.TypeAssertionExpression: case SyntaxKind.AsExpression: return isConstTypeReference((parent).type) ? undefined : getTypeFromTypeNode((parent).type); @@ -22595,19 +22692,8 @@ namespace ts { return !!forEachProperty(symbol, prop => !(prop.flags & SymbolFlags.Method)); } - function checkNonNullExpression( - node: Expression | QualifiedName, - nullDiagnostic?: DiagnosticMessage, - undefinedDiagnostic?: DiagnosticMessage, - nullOrUndefinedDiagnostic?: DiagnosticMessage, - ) { - return checkNonNullType( - checkExpression(node), - node, - nullDiagnostic, - undefinedDiagnostic, - nullOrUndefinedDiagnostic - ); + function checkNonNullExpression(node: Expression | QualifiedName) { + return checkNonNullType(checkExpression(node), node); } function isNullableType(type: Type) { @@ -22618,12 +22704,26 @@ namespace ts { return isNullableType(type) ? getNonNullableType(type) : type; } - function checkNonNullType( + function reportObjectPossiblyNullOrUndefinedError(node: Node, flags: TypeFlags) { + error(node, flags & TypeFlags.Undefined ? flags & TypeFlags.Null ? + Diagnostics.Object_is_possibly_null_or_undefined : + Diagnostics.Object_is_possibly_undefined : + Diagnostics.Object_is_possibly_null + ); + } + + function reportCannotInvokePossiblyNullOrUndefinedError(node: Node, flags: TypeFlags) { + error(node, flags & TypeFlags.Undefined ? flags & TypeFlags.Null ? + Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined : + Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined : + Diagnostics.Cannot_invoke_an_object_which_is_possibly_null + ); + } + + function checkNonNullTypeWithReporter( type: Type, node: Node, - nullDiagnostic?: DiagnosticMessage, - undefinedDiagnostic?: DiagnosticMessage, - nullOrUndefinedDiagnostic?: DiagnosticMessage + reportError: (node: Node, kind: TypeFlags) => void ): Type { if (strictNullChecks && type.flags & TypeFlags.Unknown) { error(node, Diagnostics.Object_is_of_type_unknown); @@ -22631,17 +22731,17 @@ namespace ts { } const kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & TypeFlags.Nullable; if (kind) { - error(node, kind & TypeFlags.Undefined ? kind & TypeFlags.Null ? - (nullOrUndefinedDiagnostic || Diagnostics.Object_is_possibly_null_or_undefined) : - (undefinedDiagnostic || Diagnostics.Object_is_possibly_undefined) : - (nullDiagnostic || Diagnostics.Object_is_possibly_null) - ); + reportError(node, kind); const t = getNonNullableType(type); return t.flags & (TypeFlags.Nullable | TypeFlags.Never) ? errorType : t; } return type; } + function checkNonNullType(type: Type, node: Node) { + return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError); + } + function checkNonNullNonVoidType(type: Type, node: Node): Type { const nonNullType = checkNonNullType(type, node); if (nonNullType !== errorType && nonNullType.flags & TypeFlags.Void) { @@ -22651,11 +22751,18 @@ namespace ts { } function checkPropertyAccessExpression(node: PropertyAccessExpression) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.expression, node.name); + return node.flags & NodeFlags.OptionalChain ? checkPropertyAccessChain(node as PropertyAccessChain) : + checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name); + } + + function checkPropertyAccessChain(node: PropertyAccessChain) { + const leftType = checkExpression(node.expression); + const nonOptionalType = getOptionalExpressionType(leftType, node.expression); + return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), nonOptionalType !== leftType); } function checkQualifiedName(node: QualifiedName) { - return checkPropertyAccessExpressionOrQualifiedName(node, node.left, node.right); + return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right); } function isMethodAccessForCall(node: Node) { @@ -22665,8 +22772,7 @@ namespace ts { return isCallOrNewExpression(node.parent) && node.parent.expression === node; } - function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, right: Identifier) { - const { isOptional, type: leftType } = checkOptionalExpression(node, left); + function checkPropertyAccessExpressionOrQualifiedName(node: PropertyAccessExpression | QualifiedName, left: Expression | QualifiedName, leftType: Type, right: Identifier) { const parentSymbol = getNodeLinks(left).resolvedSymbol; const assignmentKind = getAssignmentTargetKind(node); const apparentType = getApparentType(assignmentKind !== AssignmentKind.None || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType); @@ -22720,7 +22826,7 @@ namespace ts { } propType = getConstraintForLocation(getTypeOfSymbol(prop), node); } - return propagateOptionalTypeMarker(getFlowTypeOfAccessExpression(node, prop, propType, right), isOptional); + return getFlowTypeOfAccessExpression(node, prop, propType, right); } function getFlowTypeOfAccessExpression(node: ElementAccessExpression | PropertyAccessExpression | QualifiedName, prop: Symbol | undefined, propType: Type, errorNode: Node) { @@ -23077,7 +23183,17 @@ namespace ts { } function checkIndexedAccess(node: ElementAccessExpression): Type { - const { isOptional, type: exprType } = checkOptionalExpression(node, node.expression); + return node.flags & NodeFlags.OptionalChain ? checkElementAccessChain(node as ElementAccessChain) : + checkElementAccessExpression(node, checkNonNullExpression(node.expression)); + } + + function checkElementAccessChain(node: ElementAccessChain) { + const exprType = checkExpression(node.expression); + const nonOptionalType = getOptionalExpressionType(exprType, node.expression); + return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), nonOptionalType !== exprType); + } + + function checkElementAccessExpression(node: ElementAccessExpression, exprType: Type): Type { const objectType = getAssignmentTargetKind(node) !== AssignmentKind.None || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType; const indexExpression = node.argumentExpression; const indexType = checkExpression(indexExpression); @@ -23096,7 +23212,7 @@ namespace ts { AccessFlags.Writing | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? AccessFlags.NoIndexSignatures : 0) : AccessFlags.None; const indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, node, accessFlags) || errorType; - return propagateOptionalTypeMarker(checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node), isOptional); + return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node); } function checkThatExpressionIsProperSymbolReference(expression: Expression, expressionType: Type, reportError: boolean): boolean { @@ -23209,7 +23325,7 @@ namespace ts { // specialized signatures always need to be placed before non-specialized signatures regardless // of the cutoff position; see GH#1133 - if (signature.hasLiteralTypes) { + if (signatureHasLiteralTypes(signature)) { specializedIndex++; spliceIndex = specializedIndex; // The cutoff index always needs to be greater than or equal to the specialized signature index @@ -23221,7 +23337,7 @@ namespace ts { spliceIndex = index; } - result.splice(spliceIndex, 0, isOptionalCall ? createOptionalCallSignature(signature) : signature); + result.splice(spliceIndex, 0, isOptionalCall ? getOptionalCallSignature(signature) : signature); } } @@ -23572,7 +23688,20 @@ namespace ts { // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible. // If the expression is a new expression, then the check is skipped. const thisArgumentNode = getThisArgumentOfCall(node); - const thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType; + let thisArgumentType: Type; + if (thisArgumentNode) { + thisArgumentType = checkExpression(thisArgumentNode); + if (isOptionalChainRoot(thisArgumentNode.parent)) { + thisArgumentType = getNonNullableType(thisArgumentType); + } + else if (isOptionalChain(thisArgumentNode.parent)) { + thisArgumentType = removeOptionalTypeMarker(thisArgumentType); + } + } + else { + thisArgumentType = voidType; + } + const errorNode = reportErrors ? (thisArgumentNode || node) : undefined; const headMessage = Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1; if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer)) { @@ -24166,17 +24295,21 @@ namespace ts { const { min: minArgumentCount, max: maxNonRestParam } = minAndMax(candidates, getNumNonRestParameters); const parameters: Symbol[] = []; for (let i = 0; i < maxNonRestParam; i++) { - const symbols = mapDefined(candidates, ({ parameters, hasRestParameter }) => hasRestParameter ? - i < parameters.length - 1 ? parameters[i] : last(parameters) : - i < parameters.length ? parameters[i] : undefined); + const symbols = mapDefined(candidates, s => signatureHasRestParameter(s) ? + i < s.parameters.length - 1 ? s.parameters[i] : last(s.parameters) : + i < s.parameters.length ? s.parameters[i] : undefined); Debug.assert(symbols.length !== 0); parameters.push(createCombinedSymbolFromTypes(symbols, mapDefined(candidates, candidate => tryGetTypeAtPosition(candidate, i)))); } - const restParameterSymbols = mapDefined(candidates, c => c.hasRestParameter ? last(c.parameters) : undefined); - const hasRestParameter = restParameterSymbols.length !== 0; - if (hasRestParameter) { + const restParameterSymbols = mapDefined(candidates, c => signatureHasRestParameter(c) ? last(c.parameters) : undefined); + let flags = SignatureFlags.None; + if (restParameterSymbols.length !== 0) { const type = createArrayType(getUnionType(mapDefined(candidates, tryGetRestTypeOfSignature), UnionReduction.Subtype)); parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type)); + flags |= SignatureFlags.HasRestParameter; + } + if (candidates.some(signatureHasLiteralTypes)) { + flags |= SignatureFlags.HasLiteralTypes; } return createSignature( candidates[0].declaration, @@ -24186,13 +24319,12 @@ namespace ts { /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), /*typePredicate*/ undefined, minArgumentCount, - hasRestParameter, - /*hasLiteralTypes*/ candidates.some(c => c.hasLiteralTypes)); + flags); } function getNumNonRestParameters(signature: Signature): number { const numParams = signature.parameters.length; - return signature.hasRestParameter ? numParams - 1 : numParams; + return signatureHasRestParameter(signature) ? numParams - 1 : numParams; } function createCombinedSymbolFromTypes(sources: readonly Symbol[], types: Type[]): Symbol { @@ -24283,12 +24415,20 @@ namespace ts { return resolveUntypedCall(node); } - const { isOptional, type: funcType } = checkOptionalExpression( - node, + let isOptional: boolean; + let funcType = checkExpression(node.expression); + if (isCallChain(node)) { + const nonOptionalType = getOptionalExpressionType(funcType, node.expression); + isOptional = nonOptionalType !== funcType; + funcType = nonOptionalType; + } + else { + isOptional = false; + } + funcType = checkNonNullTypeWithReporter( + funcType, node.expression, - Diagnostics.Cannot_invoke_an_object_which_is_possibly_null, - Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined, - Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined + reportCannotInvokePossiblyNullOrUndefinedError ); if (funcType === silentNeverType) { @@ -24742,8 +24882,7 @@ namespace ts { typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, /*returnTypePredicate*/ undefined, 1, - /*hasRestparameter*/ false, - /*hasLiteralTypes*/ false + SignatureFlags.None ); } @@ -24782,7 +24921,7 @@ namespace ts { function isPotentiallyUncalledDecorator(decorator: Decorator, signatures: readonly Signature[]) { return signatures.length && every(signatures, signature => signature.minArgumentCount === 0 && - !signature.hasRestParameter && + !signatureHasRestParameter(signature) && signature.parameters.length < getDecoratorArgumentCount(decorator, signature)); } @@ -25198,7 +25337,7 @@ namespace ts { } function getParameterNameAtPosition(signature: Signature, pos: number) { - const paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return signature.parameters[pos].escapedName; } @@ -25217,11 +25356,11 @@ namespace ts { } function tryGetTypeAtPosition(signature: Signature, pos: number): Type | undefined { - const paramCount = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + const paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); if (pos < paramCount) { return getTypeOfParameter(signature.parameters[pos]); } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // We want to return the value undefined for an out of bounds parameter position, // so we need to check bounds here before calling getIndexedAccessType (which // otherwise would return the type 'undefined'). @@ -25258,7 +25397,7 @@ namespace ts { function getParameterCount(signature: Signature) { const length = signature.parameters.length; - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { const restType = getTypeOfSymbol(signature.parameters[length - 1]); if (isTupleType(restType)) { return length + getTypeArguments(restType).length - 1; @@ -25268,7 +25407,7 @@ namespace ts { } function getMinArgumentCount(signature: Signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); if (isTupleType(restType)) { const minLength = restType.target.minLength; @@ -25281,7 +25420,7 @@ namespace ts { } function hasEffectiveRestParameter(signature: Signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return !isTupleType(restType) || restType.target.hasRestElement; } @@ -25289,7 +25428,7 @@ namespace ts { } function getEffectiveRestType(signature: Signature) { - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { const restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]); return isTupleType(restType) ? getRestArrayTypeOfTupleType(restType) : restType; } @@ -25310,7 +25449,7 @@ namespace ts { } function inferFromAnnotatedParameters(signature: Signature, context: Signature, inferenceContext: InferenceContext) { - const len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (let i = 0; i < len; i++) { const declaration = signature.parameters[i].valueDeclaration; if (declaration.type) { @@ -25344,7 +25483,7 @@ namespace ts { assignTypeToParameterAndFixTypeParameters(signature.thisParameter!, getTypeOfSymbol(context.thisParameter)); } } - const len = signature.parameters.length - (signature.hasRestParameter ? 1 : 0); + const len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0); for (let i = 0; i < len; i++) { const parameter = signature.parameters[i]; if (!getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -25352,7 +25491,7 @@ namespace ts { assignTypeToParameterAndFixTypeParameters(parameter, contextualParameterType); } } - if (signature.hasRestParameter) { + if (signatureHasRestParameter(signature)) { // parameter might be a transient symbol generated by use of `arguments` in the function body. const parameter = last(signature.parameters); if (isTransientSymbol(parameter) || !getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) { @@ -25790,7 +25929,7 @@ namespace ts { return links.contextFreeType; } const returnType = getReturnTypeFromBody(node, checkMode); - const returnOnlySignature = createSignature(undefined, undefined, undefined, emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + const returnOnlySignature = createSignature(undefined, undefined, undefined, emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, SignatureFlags.None); const returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], emptyArray, undefined, undefined); returnOnlyType.objectFlags |= ObjectFlags.NonInferrableType; return links.contextFreeType = returnOnlyType; @@ -27255,7 +27394,18 @@ namespace ts { // Optimize for the common case of a call to a function with a single non-generic call // signature where we can just fetch the return type without checking the arguments. if (isCallExpression(expr) && expr.expression.kind !== SyntaxKind.SuperKeyword && !isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) { - const { isOptional, type: funcType } = checkOptionalExpression(expr, expr.expression); + let isOptional: boolean; + let funcType: Type; + if (isCallChain(expr)) { + funcType = checkExpression(expr.expression); + const nonOptionalType = getOptionalExpressionType(funcType, expr.expression); + isOptional = funcType !== nonOptionalType; + funcType = checkNonNullType(nonOptionalType, expr.expression); + } + else { + isOptional = false; + funcType = checkNonNullExpression(expr.expression); + } const signature = getSingleCallSignature(funcType); if (signature && !signature.typeParameters) { return propagateOptionalTypeMarker(getReturnTypeOfSignature(signature), isOptional); @@ -27530,7 +27680,7 @@ namespace ts { } else { if (typePredicate.parameterIndex >= 0) { - if (signature.hasRestParameter && typePredicate.parameterIndex === signature.parameters.length - 1) { + if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) { error(parameterName, Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter); } else { @@ -30959,10 +31109,7 @@ namespace ts { firstDefaultClause = clause; } else { - const sourceFile = getSourceFileOfNode(node); - const start = skipTrivia(sourceFile.text, clause.pos); - const end = clause.statements.length > 0 ? clause.statements[0].pos : clause.end; - grammarErrorAtPos(sourceFile, start, end - start, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); + grammarErrorOnNode(clause, Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement); hasDuplicateDefaultClause = true; } } @@ -30984,6 +31131,9 @@ namespace ts { } } forEach(clause.statements, checkSourceElement); + if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) { + error(clause, Diagnostics.Fallthrough_case_in_switch); + } }); if (node.caseBlock.locals) { registerForUnusedIdentifiersCheck(node.caseBlock); @@ -31597,15 +31747,13 @@ namespace ts { } } else if (isPrototypeProperty(base)) { - if (isPrototypeProperty(derived)) { - // method is overridden with method -- correct case + if (isPrototypeProperty(derived) || derived.flags & SymbolFlags.Property) { + // method is overridden with method or property -- correct case continue; } - else if (derived.flags & SymbolFlags.Accessor) { - errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; - } else { - errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_property; + Debug.assert(!!(derived.flags & SymbolFlags.Accessor)); + errorMessage = Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor; } } else if (base.flags & SymbolFlags.Accessor) { @@ -32147,23 +32295,6 @@ namespace ts { } } - function getFirstIdentifier(node: EntityNameOrEntityNameExpression): Identifier { - switch (node.kind) { - case SyntaxKind.Identifier: - return node; - case SyntaxKind.QualifiedName: - do { - node = node.left; - } while (node.kind !== SyntaxKind.Identifier); - return node; - case SyntaxKind.PropertyAccessExpression: - do { - node = node.expression; - } while (node.kind !== SyntaxKind.Identifier); - return node; - } - } - function getFirstNonModuleExportsIdentifier(node: EntityNameOrEntityNameExpression): Identifier { switch (node.kind) { case SyntaxKind.Identifier: @@ -32376,7 +32507,7 @@ namespace ts { // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases) const symbol = resolveName(exportedName, exportedName.escapedText, SymbolFlags.Value | SymbolFlags.Type | SymbolFlags.Namespace | SymbolFlags.Alias, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); - if (symbol && (symbol === undefinedSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { + if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) { error(exportedName, Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, idText(exportedName)); } else { @@ -34913,12 +35044,12 @@ namespace ts { typeToString(node.type ? getTypeFromTypeNode(node.type) : anyType)); } - if (type.flags & TypeFlags.Union && allTypesAssignableToKind(type, TypeFlags.StringLiteral, /*strict*/ true)) { + if (type.flags & TypeFlags.Union && allTypesAssignableToKind(type, TypeFlags.StringOrNumberLiteral, /*strict*/ true)) { return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead); } - return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_must_be_string_or_number); + return grammarErrorOnNode(parameter.name, Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number); } if (!node.type) { return grammarErrorOnNode(node, Diagnostics.An_index_signature_must_have_a_type_annotation); @@ -35905,7 +36036,7 @@ namespace ts { function checkGrammarImportCallExpression(node: ImportCall): boolean { if (moduleKind === ModuleKind.ES2015) { - return grammarErrorOnNode(node, Diagnostics.Dynamic_import_is_only_supported_when_module_flag_is_commonjs_or_esNext); + return grammarErrorOnNode(node, Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_esnext_commonjs_amd_system_or_umd); } if (node.typeArguments) { @@ -35981,4 +36112,16 @@ namespace ts { case IterationTypeKind.Next: return "nextType"; } } + + export function signatureHasRestParameter(s: Signature) { + return !!(s.flags & SignatureFlags.HasRestParameter); + } + + export function signatureHasLiteralTypes(s: Signature) { + return !!(s.flags & SignatureFlags.HasLiteralTypes); + } + + export function signatureIsOptionalCall(s: Signature) { + return !!(s.flags & SignatureFlags.IsOptionalCall); + } } diff --git a/src/compiler/commandLineParser.ts b/src/compiler/commandLineParser.ts index f7ac250984a..c9517440ac6 100644 --- a/src/compiler/commandLineParser.ts +++ b/src/compiler/commandLineParser.ts @@ -216,6 +216,15 @@ namespace ts { isCommandLineOnly: true, description: Diagnostics.Print_the_final_configuration_instead_of_building }, + { + name: "listFilesOnly", + type: "boolean", + category: Diagnostics.Command_line_Options, + affectsSemanticDiagnostics: true, + affectsEmit: true, + isCommandLineOnly: true, + description: Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing + }, // Basic { @@ -1227,7 +1236,7 @@ namespace ts { } /*@internal*/ - export function parseBuildCommand(args: string[]): ParsedBuildCommand { + export function parseBuildCommand(args: readonly string[]): ParsedBuildCommand { let buildOptionNameMap: OptionNameMap | undefined; const returnBuildOptionNameMap = () => (buildOptionNameMap || (buildOptionNameMap = createOptionNameMap(buildOpts))); const { options, fileNames: projects, errors } = parseCommandLineWorker(returnBuildOptionNameMap, [ @@ -1258,125 +1267,12 @@ namespace ts { return { buildOptions, projects, errors }; } - function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string { + /* @internal */ + export function getDiagnosticText(_message: DiagnosticMessage, ..._args: any[]): string { const diagnostic = createCompilerDiagnostic.apply(undefined, arguments); return diagnostic.messageText; } - /* @internal */ - export function printVersion() { - sys.write(getDiagnosticText(Diagnostics.Version_0, version) + sys.newLine); - } - - /* @internal */ - export function printHelp(optionsList: readonly CommandLineOption[], syntaxPrefix = "") { - const output: string[] = []; - - // We want to align our "syntax" and "examples" commands to a certain margin. - const syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length; - const examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length; - let marginLength = Math.max(syntaxLength, examplesLength); - - // Build up the syntactic skeleton. - let syntax = makePadding(marginLength - syntaxLength); - syntax += `tsc ${syntaxPrefix}[${getDiagnosticText(Diagnostics.options)}] [${getDiagnosticText(Diagnostics.file)}...]`; - - output.push(getDiagnosticText(Diagnostics.Syntax_Colon_0, syntax)); - output.push(sys.newLine + sys.newLine); - - // Build up the list of examples. - const padding = makePadding(marginLength); - output.push(getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine); - output.push(padding + "tsc --outFile file.js file.ts" + sys.newLine); - output.push(padding + "tsc @args.txt" + sys.newLine); - output.push(padding + "tsc --build tsconfig.json" + sys.newLine); - output.push(sys.newLine); - - output.push(getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine); - - // We want our descriptions to align at the same column in our output, - // so we keep track of the longest option usage string. - marginLength = 0; - const usageColumn: string[] = []; // Things like "-d, --declaration" go in here. - const descriptionColumn: string[] = []; - - const optionsDescriptionMap = createMap(); // Map between option.description and list of option.type if it is a kind - - for (const option of optionsList) { - // If an option lacks a description, - // it is not officially supported. - if (!option.description) { - continue; - } - - let usageText = " "; - if (option.shortName) { - usageText += "-" + option.shortName; - usageText += getParamType(option); - usageText += ", "; - } - - usageText += "--" + option.name; - usageText += getParamType(option); - - usageColumn.push(usageText); - let description: string; - - if (option.name === "lib") { - description = getDiagnosticText(option.description); - const element = (option).element; - const typeMap = >element.type; - optionsDescriptionMap.set(description, arrayFrom(typeMap.keys()).map(key => `'${key}'`)); - } - else { - description = getDiagnosticText(option.description); - } - - descriptionColumn.push(description); - - // Set the new margin for the description column if necessary. - marginLength = Math.max(usageText.length, marginLength); - } - - // Special case that can't fit in the loop. - const usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">"; - usageColumn.push(usageText); - descriptionColumn.push(getDiagnosticText(Diagnostics.Insert_command_line_options_and_files_from_a_file)); - marginLength = Math.max(usageText.length, marginLength); - - // Print out each row, aligning all the descriptions on the same column. - for (let i = 0; i < usageColumn.length; i++) { - const usage = usageColumn[i]; - const description = descriptionColumn[i]; - const kindsList = optionsDescriptionMap.get(description); - output.push(usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine); - - if (kindsList) { - output.push(makePadding(marginLength + 4)); - for (const kind of kindsList) { - output.push(kind + " "); - } - output.push(sys.newLine); - } - } - - for (const line of output) { - sys.write(line); - } - return; - - function getParamType(option: CommandLineOption) { - if (option.paramType !== undefined) { - return " " + getDiagnosticText(option.paramType); - } - return ""; - } - - function makePadding(paddingLength: number): string { - return Array(paddingLength + 1).join(" "); - } - } - export type DiagnosticReporter = (diagnostic: Diagnostic) => void; /** * Reports config file diagnostics @@ -1801,6 +1697,12 @@ namespace ts { references: readonly ProjectReference[] | undefined; } + /** @internal */ + export interface ConvertToTSConfigHost { + getCurrentDirectory(): string; + useCaseSensitiveFileNames: boolean; + } + /** * Generate an uncommented, complete tsconfig for use with "--showConfig" * @param configParseResult options to be generated into tsconfig.json @@ -1808,7 +1710,7 @@ namespace ts { * @param host provides current directory and case sensitivity services */ /** @internal */ - export function convertToTSConfig(configParseResult: ParsedCommandLine, configFileName: string, host: { getCurrentDirectory(): string, useCaseSensitiveFileNames: boolean }): TSConfig { + export function convertToTSConfig(configParseResult: ParsedCommandLine, configFileName: string, host: ConvertToTSConfigHost): TSConfig { const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames); const files = map( filter( @@ -1816,7 +1718,8 @@ namespace ts { (!configParseResult.configFileSpecs || !configParseResult.configFileSpecs.validatedIncludeSpecs) ? _ => true : matchesSpecs( configFileName, configParseResult.configFileSpecs.validatedIncludeSpecs, - configParseResult.configFileSpecs.validatedExcludeSpecs + configParseResult.configFileSpecs.validatedExcludeSpecs, + host, ) ), f => getRelativePathFromFile(getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), getNormalizedAbsolutePath(f, host.getCurrentDirectory()), getCanonicalFileName) @@ -1854,11 +1757,11 @@ namespace ts { return specs; } - function matchesSpecs(path: string, includeSpecs: readonly string[] | undefined, excludeSpecs: readonly string[] | undefined): (path: string) => boolean { + function matchesSpecs(path: string, includeSpecs: readonly string[] | undefined, excludeSpecs: readonly string[] | undefined, host: ConvertToTSConfigHost): (path: string) => boolean { if (!includeSpecs) return _ => true; - const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, sys.useCaseSensitiveFileNames, sys.getCurrentDirectory()); - const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, sys.useCaseSensitiveFileNames); - const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, sys.useCaseSensitiveFileNames); + const patterns = getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory()); + const excludeRe = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames); + const includeRe = patterns.includeFilePattern && getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames); if (includeRe) { if (excludeRe) { return path => !(includeRe.test(path) && !excludeRe.test(path)); @@ -2041,6 +1944,41 @@ namespace ts { } } + /* @internal */ + export function convertToOptionsWithAbsolutePaths(options: CompilerOptions, toAbsolutePath: (path: string) => string) { + const result: CompilerOptions = {}; + const optionsNameMap = getOptionNameMap().optionNameMap; + + for (const name in options) { + if (hasProperty(options, name)) { + result[name] = convertToOptionValueWithAbsolutePaths( + optionsNameMap.get(name.toLowerCase()), + options[name] as CompilerOptionsValue, + toAbsolutePath + ); + } + } + if (result.configFilePath) { + result.configFilePath = toAbsolutePath(result.configFilePath); + } + return result; + } + + function convertToOptionValueWithAbsolutePaths(option: CommandLineOption | undefined, value: CompilerOptionsValue, toAbsolutePath: (path: string) => string) { + if (option) { + if (option.type === "list") { + const values = value as readonly (string | number)[]; + if (option.element.isFilePath && values.length) { + return values.map(toAbsolutePath); + } + } + else if (option.isFilePath) { + return toAbsolutePath(value as string); + } + } + return value; + } + /** * Parse the contents of a config file (tsconfig.json). * @param json The contents of the config file to parse @@ -2604,7 +2542,7 @@ namespace ts { function normalizeNonListOptionValue(option: CommandLineOption, basePath: string, value: any): CompilerOptionsValue { if (option.isFilePath) { - value = normalizePath(combinePaths(basePath, value)); + value = getNormalizedAbsolutePath(value, basePath); if (value === "") { value = "."; } diff --git a/src/compiler/core.ts b/src/compiler/core.ts index 4532340eb5e..40a3012bbf2 100644 --- a/src/compiler/core.ts +++ b/src/compiler/core.ts @@ -42,6 +42,12 @@ namespace ts { clear(): void; } + /* @internal */ + export interface MapConstructor { + // eslint-disable-next-line @typescript-eslint/prefer-function-type + new (): Map; + } + /** ES6 Iterator type. */ export interface Iterator { next(): { value: T, done?: false } | { value: never, done: true }; @@ -66,28 +72,40 @@ namespace ts { } } +/* @internal */ +namespace ts { + // Natives + // NOTE: This must be declared in a separate block from the one below so that we don't collide with the exported definition of `Map`. + declare const Map: (new () => Map) | undefined; + + /** + * Returns the native Map implementation if it is available and compatible (i.e. supports iteration). + */ + export function tryGetNativeMap(): MapConstructor | undefined { + // Internet Explorer's Map doesn't support iteration, so don't use it. + // eslint-disable-next-line no-in-operator + return typeof Map !== "undefined" && "entries" in Map.prototype ? Map : undefined; + } +} + /* @internal */ namespace ts { export const emptyArray: never[] = [] as never[]; - /** Create a MapLike with good performance. */ - function createDictionaryObject(): MapLike { - const map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null + export const Map: MapConstructor = tryGetNativeMap() || (() => { + // NOTE: createMapShim will be defined for typescriptServices.js but not for tsc.js, so we must test for it. + if (typeof createMapShim === "function") { + return createMapShim(); + } + throw new Error("TypeScript requires an environment that provides a compatible native Map implementation."); + })(); - // Using 'delete' on an object causes V8 to put the object in dictionary mode. - // This disables creation of hidden classes, which are expensive when an object is - // constantly changing shape. - map.__ = undefined; - delete map.__; - - return map; - } - - /** Create a new map. If a template object is provided, the map will copy entries from it. */ + /** Create a new map. */ export function createMap(): Map { - return new MapCtr(); + return new Map(); } + /** Create a new map from an array of entries. */ export function createMapFromEntries(entries: [string, T][]): Map { const map = createMap(); for (const [key, value] of entries) { @@ -96,8 +114,9 @@ namespace ts { return map; } + /** Create a new map from a template object is provided, the map will copy entries from it. */ export function createMapFromTemplate(template: MapLike): Map { - const map: Map = new MapCtr(); + const map: Map = new Map(); // Copies keys/values from template. Note that for..in will not throw if // template is undefined, and instead will just exit the loop. @@ -110,204 +129,6 @@ namespace ts { return map; } - // The global Map object. This may not be available, so we must test for it. - declare const Map: (new () => Map) | undefined; - // Internet Explorer's Map doesn't support iteration, so don't use it. - // eslint-disable-next-line no-in-operator - export const MapCtr = typeof Map !== "undefined" && "entries" in Map.prototype ? Map : shimMap(); - - // Keep the class inside a function so it doesn't get compiled if it's not used. - export function shimMap(): new () => Map { - - interface MapEntry { - readonly key?: string; - value?: T; - - // Linked list references for iterators. - nextEntry?: MapEntry; - previousEntry?: MapEntry; - - /** - * Specifies if iterators should skip the next entry. - * This will be set when an entry is deleted. - * See https://github.com/Microsoft/TypeScript/pull/27292 for more information. - */ - skipNext?: boolean; - } - - class MapIterator { - private currentEntry?: MapEntry; - private selector: (key: string, value: T) => U; - - constructor(currentEntry: MapEntry, selector: (key: string, value: T) => U) { - this.currentEntry = currentEntry; - this.selector = selector; - } - - public next(): { value: U, done: false } | { value: never, done: true } { - // Navigate to the next entry. - while (this.currentEntry) { - const skipNext = !!this.currentEntry.skipNext; - this.currentEntry = this.currentEntry.nextEntry; - - if (!skipNext) { - break; - } - } - - if (this.currentEntry) { - return { value: this.selector(this.currentEntry.key!, this.currentEntry.value!), done: false }; - } - else { - return { value: undefined as never, done: true }; - } - } - } - - return class implements Map { - private data = createDictionaryObject>(); - public size = 0; - - // Linked list references for iterators. - // See https://github.com/Microsoft/TypeScript/pull/27292 - // for more information. - - /** - * The first entry in the linked list. - * Note that this is only a stub that serves as starting point - * for iterators and doesn't contain a key and a value. - */ - private readonly firstEntry: MapEntry; - private lastEntry: MapEntry; - - constructor() { - // Create a first (stub) map entry that will not contain a key - // and value but serves as starting point for iterators. - this.firstEntry = {}; - // When the map is empty, the last entry is the same as the - // first one. - this.lastEntry = this.firstEntry; - } - - get(key: string): T | undefined { - const entry = this.data[key] as MapEntry | undefined; - return entry && entry.value!; - } - - set(key: string, value: T): this { - if (!this.has(key)) { - this.size++; - - // Create a new entry that will be appended at the - // end of the linked list. - const newEntry: MapEntry = { - key, - value - }; - this.data[key] = newEntry; - - // Adjust the references. - const previousLastEntry = this.lastEntry; - previousLastEntry.nextEntry = newEntry; - newEntry.previousEntry = previousLastEntry; - this.lastEntry = newEntry; - } - else { - this.data[key].value = value; - } - - return this; - } - - has(key: string): boolean { - // eslint-disable-next-line no-in-operator - return key in this.data; - } - - delete(key: string): boolean { - if (this.has(key)) { - this.size--; - const entry = this.data[key]; - delete this.data[key]; - - // Adjust the linked list references of the neighbor entries. - const previousEntry = entry.previousEntry!; - previousEntry.nextEntry = entry.nextEntry; - if (entry.nextEntry) { - entry.nextEntry.previousEntry = previousEntry; - } - - // When the deleted entry was the last one, we need to - // adjust the lastEntry reference. - if (this.lastEntry === entry) { - this.lastEntry = previousEntry; - } - - // Adjust the forward reference of the deleted entry - // in case an iterator still references it. This allows us - // to throw away the entry, but when an active iterator - // (which points to the current entry) continues, it will - // navigate to the entry that originally came before the - // current one and skip it. - entry.previousEntry = undefined; - entry.nextEntry = previousEntry; - entry.skipNext = true; - - return true; - } - return false; - } - - clear(): void { - this.data = createDictionaryObject>(); - this.size = 0; - - // Reset the linked list. Note that we must adjust the forward - // references of the deleted entries to ensure iterators stuck - // in the middle of the list don't continue with deleted entries, - // but can continue with new entries added after the clear() - // operation. - const firstEntry = this.firstEntry; - let currentEntry = firstEntry.nextEntry; - while (currentEntry) { - const nextEntry = currentEntry.nextEntry; - currentEntry.previousEntry = undefined; - currentEntry.nextEntry = firstEntry; - currentEntry.skipNext = true; - - currentEntry = nextEntry; - } - firstEntry.nextEntry = undefined; - this.lastEntry = firstEntry; - } - - keys(): Iterator { - return new MapIterator(this.firstEntry, key => key); - } - - values(): Iterator { - return new MapIterator(this.firstEntry, (_key, value) => value); - } - - entries(): Iterator<[string, T]> { - return new MapIterator(this.firstEntry, (key, value) => [key, value] as [string, T]); - } - - forEach(action: (value: T, key: string) => void): void { - const iterator = this.entries(); - while (true) { - const iterResult = iterator.next(); - if (iterResult.done) { - break; - } - - const [key, value] = iterResult.value; - action(value, key); - } - } - }; - } - export function length(array: readonly any[] | undefined): number { return array ? array.length : 0; } @@ -2052,20 +1873,6 @@ namespace ts { return str.indexOf(substring) !== -1; } - export function fileExtensionIs(path: string, extension: string): boolean { - return path.length > extension.length && endsWith(path, extension); - } - - export function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean { - for (const extension of extensions) { - if (fileExtensionIs(path, extension)) { - return true; - } - } - - return false; - } - /** * Takes a string like "jquery-min.4.2.3" and returns "jquery" */ diff --git a/src/compiler/debug.ts b/src/compiler/debug.ts index 09d230f24e9..40ac6c9c94f 100644 --- a/src/compiler/debug.ts +++ b/src/compiler/debug.ts @@ -221,6 +221,40 @@ namespace ts { let isDebugInfoEnabled = false; + interface ExtendedDebugModule { + init(_ts: typeof ts): void; + formatControlFlowGraph(flowNode: FlowNode): string; + } + + let extendedDebugModule: ExtendedDebugModule | undefined; + + function extendedDebug() { + enableDebugInfo(); + if (!extendedDebugModule) { + throw new Error("Debugging helpers could not be loaded."); + } + return extendedDebugModule; + } + + export function printControlFlowGraph(flowNode: FlowNode) { + return console.log(formatControlFlowGraph(flowNode)); + } + + export function formatControlFlowGraph(flowNode: FlowNode) { + return extendedDebug().formatControlFlowGraph(flowNode); + } + + export function attachFlowNodeDebugInfo(flowNode: FlowNode) { + if (isDebugInfoEnabled) { + if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator + Object.defineProperties(flowNode, { + __debugFlowFlags: { get(this: FlowNode) { return formatEnum(this.flags, (ts as any).FlowFlags, /*isFlags*/ true); } }, + __debugToString: { value(this: FlowNode) { return formatControlFlowGraph(this); } } + }); + } + } + } + /** * Injects debug information into frequently used types. */ @@ -266,6 +300,21 @@ namespace ts { } } + // attempt to load extended debugging information + try { + if (sys && sys.require) { + const basePath = getDirectoryPath(resolvePath(sys.getExecutingFilePath())); + const result = sys.require(basePath, "./compiler-debug") as RequireResult; + if (!result.error) { + result.module.init(ts); + extendedDebugModule = result.module; + } + } + } + catch { + // do nothing + } + isDebugInfoEnabled = true; } diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.json index c5bde22eaba..5cb18c1f333 100644 --- a/src/compiler/diagnosticMessages.json +++ b/src/compiler/diagnosticMessages.json @@ -71,7 +71,7 @@ "category": "Error", "code": 1022 }, - "An index signature parameter type must be 'string' or 'number'.": { + "An index signature parameter type must be either 'string' or 'number'.": { "category": "Error", "code": 1023 }, @@ -903,7 +903,7 @@ "category": "Error", "code": 1322 }, - "Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'.": { + "Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'.": { "category": "Error", "code": 1323 }, @@ -1043,6 +1043,10 @@ "category": "Error", "code": 1358 }, + "Identifier expected. '{0}' is a reserved word that cannot be used here.": { + "category": "Error", + "code": 1359 + }, "The types of '{0}' are incompatible between these types.": { "category": "Error", @@ -1557,10 +1561,6 @@ "category": "Error", "code": 2423 }, - "Class '{0}' defines instance member function '{1}', but extended class '{2}' defines it as instance member property.": { - "category": "Error", - "code": 2424 - }, "Class '{0}' defines instance member property '{1}', but extended class '{2}' defines it as instance member function.": { "category": "Error", "code": 2425 @@ -2249,6 +2249,14 @@ "category": "Error", "code": 2612 }, + "Module '{0}' has no default export. Did you mean to use 'import { {1} } from {0}' instead?": { + "category": "Error", + "code": 2613 + }, + "Module '{0}' has no exported member '{1}'. Did you mean to use 'import {1} from {0}' instead?": { + "category": "Error", + "code": 2614 + }, "Cannot augment module '{0}' with value exports because it resolves to a non-module entity.": { "category": "Error", @@ -4303,6 +4311,10 @@ "category": "Message", "code": 6502 }, + "Print names of files that are part of the compilation and then stop processing.": { + "category": "Message", + "code": 6503 + }, "Variable '{0}' implicitly has an '{1}' type.": { "category": "Error", diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.ts index d87157aa753..cbff1fb2512 100644 --- a/src/compiler/emitter.ts +++ b/src/compiler/emitter.ts @@ -393,7 +393,9 @@ namespace ts { declarationFilePath: string | undefined, declarationMapPath: string | undefined, relativeToBuildInfo: (path: string) => string) { - if (!sourceFileOrBundle || !declarationFilePath) { + if (!sourceFileOrBundle) return; + if (!declarationFilePath) { + if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly) emitSkipped = true; return; } const sourceFiles = isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles; diff --git a/src/compiler/factory.ts b/src/compiler/factory.ts index 321fee7e6a8..7ec85bd94c1 100644 --- a/src/compiler/factory.ts +++ b/src/compiler/factory.ts @@ -1065,7 +1065,9 @@ namespace ts { } export function updatePropertyAccess(node: PropertyAccessExpression, expression: Expression, name: Identifier) { - Debug.assert(!(node.flags & NodeFlags.OptionalChain), "Cannot update a PropertyAccessChain using updatePropertyAccess. Use updatePropertyAccessChain instead."); + if (isOptionalChain(node)) { + return updatePropertyAccessChain(node, expression, node.questionDotToken, name); + } // Because we are updating existed propertyAccess we want to inherit its emitFlags // instead of using the default from createPropertyAccess return node.expression !== expression @@ -1103,7 +1105,9 @@ namespace ts { } export function updateElementAccess(node: ElementAccessExpression, expression: Expression, argumentExpression: Expression) { - Debug.assert(!(node.flags & NodeFlags.OptionalChain), "Cannot update an ElementAccessChain using updateElementAccess. Use updateElementAccessChain instead."); + if (isOptionalChain(node)) { + return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression); + } return node.expression !== expression || node.argumentExpression !== argumentExpression ? updateNode(createElementAccess(expression, argumentExpression), node) @@ -1137,7 +1141,9 @@ namespace ts { } export function updateCall(node: CallExpression, expression: Expression, typeArguments: readonly TypeNode[] | undefined, argumentsArray: readonly Expression[]) { - Debug.assert(!(node.flags & NodeFlags.OptionalChain), "Cannot update a CallChain using updateCall. Use updateCallChain instead."); + if (isOptionalChain(node)) { + return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray); + } return node.expression !== expression || node.typeArguments !== typeArguments || node.arguments !== argumentsArray @@ -1805,7 +1811,7 @@ namespace ts { const node = createSynthesizedNode(SyntaxKind.ForOfStatement); node.awaitModifier = awaitModifier; node.initializer = initializer; - node.expression = expression; + node.expression = isCommaSequence(expression) ? createParen(expression) : expression; node.statement = asEmbeddedStatement(statement); return node; } @@ -2974,7 +2980,10 @@ namespace ts { (texts || (texts = [])).push(prependNode); break; case BundleFileSectionKind.Internal: - if (stripInternal) break; + if (stripInternal) { + if (!texts) texts = []; + break; + } // falls through case BundleFileSectionKind.Text: @@ -4730,7 +4739,7 @@ namespace ts { const conditionalPrecedence = getOperatorPrecedence(SyntaxKind.ConditionalExpression, SyntaxKind.QuestionToken); const emittedCondition = skipPartiallyEmittedExpressions(condition); const conditionPrecedence = getExpressionPrecedence(emittedCondition); - if (compareValues(conditionPrecedence, conditionalPrecedence) === Comparison.LessThan) { + if (compareValues(conditionPrecedence, conditionalPrecedence) !== Comparison.GreaterThan) { return createParen(condition); } return condition; diff --git a/src/compiler/moduleSpecifiers.ts b/src/compiler/moduleSpecifiers.ts index 4855ec9a702..564cb4db2c4 100644 --- a/src/compiler/moduleSpecifiers.ts +++ b/src/compiler/moduleSpecifiers.ts @@ -317,9 +317,13 @@ namespace ts.moduleSpecifiers { // If the module could be imported by a directory name, use that directory's name const moduleSpecifier = packageNameOnly ? moduleFileName : getDirectoryOrExtensionlessFileName(moduleFileName); + const globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); // Get a path that's relative to node_modules or the importing file's path // if node_modules folder is in this folder or any of its parent folders, no need to keep it. - if (!startsWith(sourceDirectory, getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)))) return undefined; + const pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex)); + if (!(startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) { + return undefined; + } // If the module was found in @types, get the actual Node package name const nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1); diff --git a/src/compiler/parser.ts b/src/compiler/parser.ts index fcf0353b189..146b74c3cb8 100644 --- a/src/compiler/parser.ts +++ b/src/compiler/parser.ts @@ -1401,7 +1401,14 @@ namespace ts { // Only for end of file because the error gets reported incorrectly on embedded script tags. const reportAtCurrentPosition = token() === SyntaxKind.EndOfFileToken; - return createMissingNode(SyntaxKind.Identifier, reportAtCurrentPosition, diagnosticMessage || Diagnostics.Identifier_expected); + const isReservedWord = scanner.isReservedWord(); + const msgArg = scanner.getTokenText(); + + const defaultMessage = isReservedWord ? + Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here : + Diagnostics.Identifier_expected; + + return createMissingNode(SyntaxKind.Identifier, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg); } function parseIdentifier(diagnosticMessage?: DiagnosticMessage): Identifier { diff --git a/src/compiler/path.ts b/src/compiler/path.ts new file mode 100644 index 00000000000..d7d8d964d54 --- /dev/null +++ b/src/compiler/path.ts @@ -0,0 +1,855 @@ +/* @internal */ +namespace ts { + /** + * Internally, we represent paths as strings with '/' as the directory separator. + * When we make system calls (eg: LanguageServiceHost.getDirectory()), + * we expect the host to correctly handle paths in our specified format. + */ + export const directorySeparator = "/"; + const altDirectorySeparator = "\\"; + const urlSchemeSeparator = "://"; + const backslashRegExp = /\\/g; + + //// Path Tests + + /** + * Determines whether a charCode corresponds to `/` or `\`. + */ + export function isAnyDirectorySeparator(charCode: number): boolean { + return charCode === CharacterCodes.slash || charCode === CharacterCodes.backslash; + } + + /** + * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.). + */ + export function isUrl(path: string) { + return getEncodedRootLength(path) < 0; + } + + /** + * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path + * like `c:`, `c:\` or `c:/`). + */ + export function isRootedDiskPath(path: string) { + return getEncodedRootLength(path) > 0; + } + + /** + * Determines whether a path consists only of a path root. + */ + export function isDiskPathRoot(path: string) { + const rootLength = getEncodedRootLength(path); + return rootLength > 0 && rootLength === path.length; + } + + /** + * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.). + * + * ```ts + * // POSIX + * pathIsAbsolute("/path/to/file.ext") === true + * // DOS + * pathIsAbsolute("c:/path/to/file.ext") === true + * // URL + * pathIsAbsolute("file:///path/to/file.ext") === true + * // Non-absolute + * pathIsAbsolute("path/to/file.ext") === false + * pathIsAbsolute("./path/to/file.ext") === false + * ``` + */ + export function pathIsAbsolute(path: string): boolean { + return getEncodedRootLength(path) !== 0; + } + + /** + * Determines whether a path starts with a relative path component (i.e. `.` or `..`). + */ + export function pathIsRelative(path: string): boolean { + return /^\.\.?($|[\\/])/.test(path); + } + + export function hasExtension(fileName: string): boolean { + return stringContains(getBaseFileName(fileName), "."); + } + + export function fileExtensionIs(path: string, extension: string): boolean { + return path.length > extension.length && endsWith(path, extension); + } + + export function fileExtensionIsOneOf(path: string, extensions: readonly string[]): boolean { + for (const extension of extensions) { + if (fileExtensionIs(path, extension)) { + return true; + } + } + + return false; + } + + /** + * Determines whether a path has a trailing separator (`/` or `\\`). + */ + export function hasTrailingDirectorySeparator(path: string) { + return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1)); + } + + //// Path Parsing + + function isVolumeCharacter(charCode: number) { + return (charCode >= CharacterCodes.a && charCode <= CharacterCodes.z) || + (charCode >= CharacterCodes.A && charCode <= CharacterCodes.Z); + } + + function getFileUrlVolumeSeparatorEnd(url: string, start: number) { + const ch0 = url.charCodeAt(start); + if (ch0 === CharacterCodes.colon) return start + 1; + if (ch0 === CharacterCodes.percent && url.charCodeAt(start + 1) === CharacterCodes._3) { + const ch2 = url.charCodeAt(start + 2); + if (ch2 === CharacterCodes.a || ch2 === CharacterCodes.A) return start + 3; + } + return -1; + } + + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * If the root is part of a URL, the twos-complement of the root length is returned. + */ + function getEncodedRootLength(path: string): number { + if (!path) return 0; + const ch0 = path.charCodeAt(0); + + // POSIX or UNC + if (ch0 === CharacterCodes.slash || ch0 === CharacterCodes.backslash) { + if (path.charCodeAt(1) !== ch0) return 1; // POSIX: "/" (or non-normalized "\") + + const p1 = path.indexOf(ch0 === CharacterCodes.slash ? directorySeparator : altDirectorySeparator, 2); + if (p1 < 0) return path.length; // UNC: "//server" or "\\server" + + return p1 + 1; // UNC: "//server/" or "\\server\" + } + + // DOS + if (isVolumeCharacter(ch0) && path.charCodeAt(1) === CharacterCodes.colon) { + const ch2 = path.charCodeAt(2); + if (ch2 === CharacterCodes.slash || ch2 === CharacterCodes.backslash) return 3; // DOS: "c:/" or "c:\" + if (path.length === 2) return 2; // DOS: "c:" (but not "c:d") + } + + // URL + const schemeEnd = path.indexOf(urlSchemeSeparator); + if (schemeEnd !== -1) { + const authorityStart = schemeEnd + urlSchemeSeparator.length; + const authorityEnd = path.indexOf(directorySeparator, authorityStart); + if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" + // For local "file" URLs, include the leading DOS volume (if present). + // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a + // special case interpreted as "the machine from which the URL is being interpreted". + const scheme = path.slice(0, schemeEnd); + const authority = path.slice(authorityStart, authorityEnd); + if (scheme === "file" && (authority === "" || authority === "localhost") && + isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { + const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); + if (volumeSeparatorEnd !== -1) { + if (path.charCodeAt(volumeSeparatorEnd) === CharacterCodes.slash) { + // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" + return ~(volumeSeparatorEnd + 1); + } + if (volumeSeparatorEnd === path.length) { + // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" + // but not "file:///c:d" or "file:///c%3ad" + return ~volumeSeparatorEnd; + } + } + } + return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" + } + return ~path.length; // URL: "file://server", "http://server" + } + + // relative + return 0; + } + + /** + * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). + * + * For example: + * ```ts + * getRootLength("a") === 0 // "" + * getRootLength("/") === 1 // "/" + * getRootLength("c:") === 2 // "c:" + * getRootLength("c:d") === 0 // "" + * getRootLength("c:/") === 3 // "c:/" + * getRootLength("c:\\") === 3 // "c:\\" + * getRootLength("//server") === 7 // "//server" + * getRootLength("//server/share") === 8 // "//server/" + * getRootLength("\\\\server") === 7 // "\\\\server" + * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" + * getRootLength("file:///path") === 8 // "file:///" + * getRootLength("file:///c:") === 10 // "file:///c:" + * getRootLength("file:///c:d") === 8 // "file:///" + * getRootLength("file:///c:/path") === 11 // "file:///c:/" + * getRootLength("file://server") === 13 // "file://server" + * getRootLength("file://server/path") === 14 // "file://server/" + * getRootLength("http://server") === 13 // "http://server" + * getRootLength("http://server/path") === 14 // "http://server/" + * ``` + */ + export function getRootLength(path: string) { + const rootLength = getEncodedRootLength(path); + return rootLength < 0 ? ~rootLength : rootLength; + } + + /** + * Returns the path except for its basename. Semantics align with NodeJS's `path.dirname` + * except that we support URLs as well. + * + * ```ts + * // POSIX + * getDirectoryPath("/path/to/file.ext") === "/path/to" + * getDirectoryPath("/path/to/") === "/path" + * getDirectoryPath("/") === "/" + * // DOS + * getDirectoryPath("c:/path/to/file.ext") === "c:/path/to" + * getDirectoryPath("c:/path/to/") === "c:/path" + * getDirectoryPath("c:/") === "c:/" + * getDirectoryPath("c:") === "c:" + * // URL + * getDirectoryPath("http://typescriptlang.org/path/to/file.ext") === "http://typescriptlang.org/path/to" + * getDirectoryPath("http://typescriptlang.org/path/to") === "http://typescriptlang.org/path" + * getDirectoryPath("http://typescriptlang.org/") === "http://typescriptlang.org/" + * getDirectoryPath("http://typescriptlang.org") === "http://typescriptlang.org" + * ``` + */ + export function getDirectoryPath(path: Path): Path; + /** + * Returns the path except for its basename. Semantics align with NodeJS's `path.dirname` + * except that we support URLs as well. + * + * ```ts + * // POSIX + * getDirectoryPath("/path/to/file.ext") === "/path/to" + * getDirectoryPath("/path/to/") === "/path" + * getDirectoryPath("/") === "/" + * // DOS + * getDirectoryPath("c:/path/to/file.ext") === "c:/path/to" + * getDirectoryPath("c:/path/to/") === "c:/path" + * getDirectoryPath("c:/") === "c:/" + * getDirectoryPath("c:") === "c:" + * // URL + * getDirectoryPath("http://typescriptlang.org/path/to/file.ext") === "http://typescriptlang.org/path/to" + * getDirectoryPath("http://typescriptlang.org/path/to") === "http://typescriptlang.org/path" + * getDirectoryPath("http://typescriptlang.org/") === "http://typescriptlang.org/" + * getDirectoryPath("http://typescriptlang.org") === "http://typescriptlang.org" + * getDirectoryPath("file://server/path/to/file.ext") === "file://server/path/to" + * getDirectoryPath("file://server/path/to") === "file://server/path" + * getDirectoryPath("file://server/") === "file://server/" + * getDirectoryPath("file://server") === "file://server" + * getDirectoryPath("file:///path/to/file.ext") === "file:///path/to" + * getDirectoryPath("file:///path/to") === "file:///path" + * getDirectoryPath("file:///") === "file:///" + * getDirectoryPath("file://") === "file://" + * ``` + */ + export function getDirectoryPath(path: string): string; + export function getDirectoryPath(path: string): string { + path = normalizeSlashes(path); + + // If the path provided is itself the root, then return it. + const rootLength = getRootLength(path); + if (rootLength === path.length) return path; + + // return the leading portion of the path up to the last (non-terminal) directory separator + // but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator))); + } + + /** + * Returns the path except for its containing directory name. + * Semantics align with NodeJS's `path.basename` except that we support URL's as well. + * + * ```ts + * // POSIX + * getBaseFileName("/path/to/file.ext") === "file.ext" + * getBaseFileName("/path/to/") === "to" + * getBaseFileName("/") === "" + * // DOS + * getBaseFileName("c:/path/to/file.ext") === "file.ext" + * getBaseFileName("c:/path/to/") === "to" + * getBaseFileName("c:/") === "" + * getBaseFileName("c:") === "" + * // URL + * getBaseFileName("http://typescriptlang.org/path/to/file.ext") === "file.ext" + * getBaseFileName("http://typescriptlang.org/path/to/") === "to" + * getBaseFileName("http://typescriptlang.org/") === "" + * getBaseFileName("http://typescriptlang.org") === "" + * getBaseFileName("file://server/path/to/file.ext") === "file.ext" + * getBaseFileName("file://server/path/to/") === "to" + * getBaseFileName("file://server/") === "" + * getBaseFileName("file://server") === "" + * getBaseFileName("file:///path/to/file.ext") === "file.ext" + * getBaseFileName("file:///path/to/") === "to" + * getBaseFileName("file:///") === "" + * getBaseFileName("file://") === "" + * ``` + */ + export function getBaseFileName(path: string): string; + /** + * Gets the portion of a path following the last (non-terminal) separator (`/`). + * Semantics align with NodeJS's `path.basename` except that we support URL's as well. + * If the base name has any one of the provided extensions, it is removed. + * + * ```ts + * getBaseFileName("/path/to/file.ext", ".ext", true) === "file" + * getBaseFileName("/path/to/file.js", ".ext", true) === "file.js" + * getBaseFileName("/path/to/file.js", [".ext", ".js"], true) === "file" + * getBaseFileName("/path/to/file.ext", ".EXT", false) === "file.ext" + * ``` + */ + export function getBaseFileName(path: string, extensions: string | readonly string[], ignoreCase: boolean): string; + export function getBaseFileName(path: string, extensions?: string | readonly string[], ignoreCase?: boolean) { + path = normalizeSlashes(path); + + // if the path provided is itself the root, then it has not file name. + const rootLength = getRootLength(path); + if (rootLength === path.length) return ""; + + // return the trailing portion of the path starting after the last (non-terminal) directory + // separator but not including any trailing directory separator. + path = removeTrailingDirectorySeparator(path); + const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1)); + const extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; + return extension ? name.slice(0, name.length - extension.length) : name; + } + + function tryGetExtensionFromPath(path: string, extension: string, stringEqualityComparer: (a: string, b: string) => boolean) { + if (!startsWith(extension, ".")) extension = "." + extension; + if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === CharacterCodes.dot) { + const pathExtension = path.slice(path.length - extension.length); + if (stringEqualityComparer(pathExtension, extension)) { + return pathExtension; + } + } + } + + function getAnyExtensionFromPathWorker(path: string, extensions: string | readonly string[], stringEqualityComparer: (a: string, b: string) => boolean) { + if (typeof extensions === "string") { + return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || ""; + } + for (const extension of extensions) { + const result = tryGetExtensionFromPath(path, extension, stringEqualityComparer); + if (result) return result; + } + return ""; + } + + /** + * Gets the file extension for a path. + * + * ```ts + * getAnyExtensionFromPath("/path/to/file.ext") === ".ext" + * getAnyExtensionFromPath("/path/to/file.ext/") === ".ext" + * getAnyExtensionFromPath("/path/to/file") === "" + * getAnyExtensionFromPath("/path/to.ext/file") === "" + * ``` + */ + export function getAnyExtensionFromPath(path: string): string; + /** + * Gets the file extension for a path, provided it is one of the provided extensions. + * + * ```ts + * getAnyExtensionFromPath("/path/to/file.ext", ".ext", true) === ".ext" + * getAnyExtensionFromPath("/path/to/file.js", ".ext", true) === "" + * getAnyExtensionFromPath("/path/to/file.js", [".ext", ".js"], true) === ".js" + * getAnyExtensionFromPath("/path/to/file.ext", ".EXT", false) === "" + */ + export function getAnyExtensionFromPath(path: string, extensions: string | readonly string[], ignoreCase: boolean): string; + export function getAnyExtensionFromPath(path: string, extensions?: string | readonly string[], ignoreCase?: boolean): string { + // Retrieves any string from the final "." onwards from a base file name. + // Unlike extensionFromPath, which throws an exception on unrecognized extensions. + if (extensions) { + return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive); + } + const baseFileName = getBaseFileName(path); + const extensionIndex = baseFileName.lastIndexOf("."); + if (extensionIndex >= 0) { + return baseFileName.substring(extensionIndex); + } + return ""; + } + + function pathComponents(path: string, rootLength: number) { + const root = path.substring(0, rootLength); + const rest = path.substring(rootLength).split(directorySeparator); + if (rest.length && !lastOrUndefined(rest)) rest.pop(); + return [root, ...rest]; + } + + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is not normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * // POSIX + * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"] + * getPathComponents("/path/to/") === ["/", "path", "to"] + * getPathComponents("/") === ["/"] + * // DOS + * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"] + * getPathComponents("c:/path/to/") === ["c:/", "path", "to"] + * getPathComponents("c:/") === ["c:/"] + * getPathComponents("c:") === ["c:"] + * // URL + * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"] + * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"] + * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"] + * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"] + * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"] + * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"] + * getPathComponents("file://server/") === ["file://server/"] + * getPathComponents("file://server") === ["file://server"] + * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"] + * getPathComponents("file:///path/to/") === ["file:///", "path", "to"] + * getPathComponents("file:///") === ["file:///"] + * getPathComponents("file://") === ["file://"] + */ + export function getPathComponents(path: string, currentDirectory = "") { + path = combinePaths(currentDirectory, path); + return pathComponents(path, getRootLength(path)); + } + + //// Path Formatting + + /** + * Formats a parsed path consisting of a root component (at index 0) and zero or more path + * segments (at indices > 0). + * + * ```ts + * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext" + * ``` + */ + export function getPathFromPathComponents(pathComponents: readonly string[]) { + if (pathComponents.length === 0) return ""; + + const root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); + return root + pathComponents.slice(1).join(directorySeparator); + } + + //// Path Normalization + + /** + * Normalize path separators, converting `\` into `/`. + */ + export function normalizeSlashes(path: string): string { + return path.replace(backslashRegExp, directorySeparator); + } + + /** + * Reduce an array of path components to a more simplified path by navigating any + * `"."` or `".."` entries in the path. + */ + export function reducePathComponents(components: readonly string[]) { + if (!some(components)) return []; + const reduced = [components[0]]; + for (let i = 1; i < components.length; i++) { + const component = components[i]; + if (!component) continue; + if (component === ".") continue; + if (component === "..") { + if (reduced.length > 1) { + if (reduced[reduced.length - 1] !== "..") { + reduced.pop(); + continue; + } + } + else if (reduced[0]) continue; + } + reduced.push(component); + } + return reduced; + } + + /** + * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified. + * + * ```ts + * // Non-rooted + * combinePaths("path", "to", "file.ext") === "path/to/file.ext" + * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext" + * // POSIX + * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext" + * combinePaths("/path", "/to", "file.ext") === "/to/file.ext" + * // DOS + * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext" + * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext" + * // URL + * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext" + * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext" + * ``` + */ + export function combinePaths(path: string, ...paths: (string | undefined)[]): string { + if (path) path = normalizeSlashes(path); + for (let relativePath of paths) { + if (!relativePath) continue; + relativePath = normalizeSlashes(relativePath); + if (!path || getRootLength(relativePath) !== 0) { + path = relativePath; + } + else { + path = ensureTrailingDirectorySeparator(path) + relativePath; + } + } + return path; + } + + /** + * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any + * `.` and `..` path components are resolved. Trailing directory separators are preserved. + * + * ```ts + * resolvePath("/path", "to", "file.ext") === "path/to/file.ext" + * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/" + * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext" + * ``` + */ + export function resolvePath(path: string, ...paths: (string | undefined)[]): string { + return normalizePath(some(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path)); + } + + /** + * Parse a path into an array containing a root component (at index 0) and zero or more path + * components (at indices > 0). The result is normalized. + * If the path is relative, the root component is `""`. + * If the path is absolute, the root component includes the first path separator (`/`). + * + * ```ts + * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"] + */ + export function getNormalizedPathComponents(path: string, currentDirectory: string | undefined) { + return reducePathComponents(getPathComponents(path, currentDirectory)); + } + + export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined) { + return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); + } + + export function normalizePath(path: string): string { + path = normalizeSlashes(path); + const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path))); + return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized; + } + + function getPathWithoutRoot(pathComponents: readonly string[]) { + if (pathComponents.length === 0) return ""; + return pathComponents.slice(1).join(directorySeparator); + } + + export function getNormalizedAbsolutePathWithoutRoot(fileName: string, currentDirectory: string | undefined) { + return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); + } + + export function toPath(fileName: string, basePath: string | undefined, getCanonicalFileName: (path: string) => string): Path { + const nonCanonicalizedPath = isRootedDiskPath(fileName) + ? normalizePath(fileName) + : getNormalizedAbsolutePath(fileName, basePath); + return getCanonicalFileName(nonCanonicalizedPath); + } + + export function normalizePathAndParts(path: string): { path: string, parts: string[] } { + path = normalizeSlashes(path); + const [root, ...parts] = reducePathComponents(getPathComponents(path)); + if (parts.length) { + const joinedParts = root + parts.join(directorySeparator); + return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts }; + } + else { + return { path: root, parts }; + } + } + + //// Path Mutation + + /** + * Removes a trailing directory separator from a path, if it does not already have one. + * + * ```ts + * removeTrailingDirectorySeparator("/path/to/file.ext") === "/path/to/file.ext" + * removeTrailingDirectorySeparator("/path/to/file.ext/") === "/path/to/file.ext" + * ``` + */ + export function removeTrailingDirectorySeparator(path: Path): Path; + export function removeTrailingDirectorySeparator(path: string): string; + export function removeTrailingDirectorySeparator(path: string) { + if (hasTrailingDirectorySeparator(path)) { + return path.substr(0, path.length - 1); + } + + return path; + } + + /** + * Adds a trailing directory separator to a path, if it does not already have one. + * + * ```ts + * ensureTrailingDirectorySeparator("/path/to/file.ext") === "/path/to/file.ext/" + * ensureTrailingDirectorySeparator("/path/to/file.ext/") === "/path/to/file.ext/" + * ``` + */ + export function ensureTrailingDirectorySeparator(path: Path): Path; + export function ensureTrailingDirectorySeparator(path: string): string; + export function ensureTrailingDirectorySeparator(path: string) { + if (!hasTrailingDirectorySeparator(path)) { + return path + directorySeparator; + } + + return path; + } + + /** + * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed + * with `./` or `../`) so as not to be confused with an unprefixed module name. + * + * ```ts + * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext" + * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext" + * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext" + * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext" + * ``` + */ + export function ensurePathIsNonModuleName(path: string): string { + return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path; + } + + /** + * Changes the extension of a path to the provided extension. + * + * ```ts + * changeAnyExtension("/path/to/file.ext", ".js") === "/path/to/file.js" + * ``` + */ + export function changeAnyExtension(path: string, ext: string): string; + /** + * Changes the extension of a path to the provided extension if it has one of the provided extensions. + * + * ```ts + * changeAnyExtension("/path/to/file.ext", ".js", ".ext") === "/path/to/file.js" + * changeAnyExtension("/path/to/file.ext", ".js", ".ts") === "/path/to/file.ext" + * changeAnyExtension("/path/to/file.ext", ".js", [".ext", ".ts"]) === "/path/to/file.js" + * ``` + */ + export function changeAnyExtension(path: string, ext: string, extensions: string | readonly string[], ignoreCase: boolean): string; + export function changeAnyExtension(path: string, ext: string, extensions?: string | readonly string[], ignoreCase?: boolean) { + const pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); + return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; + } + + //// Path Comparisons + + // check path for these segments: '', '.'. '..' + const relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; + + function comparePathsWorker(a: string, b: string, componentComparer: (a: string, b: string) => Comparison) { + if (a === b) return Comparison.EqualTo; + if (a === undefined) return Comparison.LessThan; + if (b === undefined) return Comparison.GreaterThan; + + // NOTE: Performance optimization - shortcut if the root segments differ as there would be no + // need to perform path reduction. + const aRoot = a.substring(0, getRootLength(a)); + const bRoot = b.substring(0, getRootLength(b)); + const result = compareStringsCaseInsensitive(aRoot, bRoot); + if (result !== Comparison.EqualTo) { + return result; + } + + // NOTE: Performance optimization - shortcut if there are no relative path segments in + // the non-root portion of the path + const aRest = a.substring(aRoot.length); + const bRest = b.substring(bRoot.length); + if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { + return componentComparer(aRest, bRest); + } + + // The path contains a relative path segment. Normalize the paths and perform a slower component + // by component comparison. + const aComponents = reducePathComponents(getPathComponents(a)); + const bComponents = reducePathComponents(getPathComponents(b)); + const sharedLength = Math.min(aComponents.length, bComponents.length); + for (let i = 1; i < sharedLength; i++) { + const result = componentComparer(aComponents[i], bComponents[i]); + if (result !== Comparison.EqualTo) { + return result; + } + } + return compareValues(aComponents.length, bComponents.length); + } + + /** + * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively. + */ + export function comparePathsCaseSensitive(a: string, b: string) { + return comparePathsWorker(a, b, compareStringsCaseSensitive); + } + + /** + * Performs a case-insensitive comparison of two paths. + */ + export function comparePathsCaseInsensitive(a: string, b: string) { + return comparePathsWorker(a, b, compareStringsCaseInsensitive); + } + + /** + * Compare two paths using the provided case sensitivity. + */ + export function comparePaths(a: string, b: string, ignoreCase?: boolean): Comparison; + export function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison; + export function comparePaths(a: string, b: string, currentDirectory?: string | boolean, ignoreCase?: boolean) { + if (typeof currentDirectory === "string") { + a = combinePaths(currentDirectory, a); + b = combinePaths(currentDirectory, b); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + return comparePathsWorker(a, b, getStringComparer(ignoreCase)); + } + + /** + * Determines whether a `parent` path contains a `child` path using the provide case sensitivity. + */ + export function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean; + export function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean; + export function containsPath(parent: string, child: string, currentDirectory?: string | boolean, ignoreCase?: boolean) { + if (typeof currentDirectory === "string") { + parent = combinePaths(currentDirectory, parent); + child = combinePaths(currentDirectory, child); + } + else if (typeof currentDirectory === "boolean") { + ignoreCase = currentDirectory; + } + if (parent === undefined || child === undefined) return false; + if (parent === child) return true; + const parentComponents = reducePathComponents(getPathComponents(parent)); + const childComponents = reducePathComponents(getPathComponents(child)); + if (childComponents.length < parentComponents.length) { + return false; + } + + const componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; + for (let i = 0; i < parentComponents.length; i++) { + const equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer; + if (!equalityComparer(parentComponents[i], childComponents[i])) { + return false; + } + } + + return true; + } + + /** + * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback. + * Comparison is case-sensitive between the canonical paths. + * + * @deprecated Use `containsPath` if possible. + */ + export function startsWithDirectory(fileName: string, directoryName: string, getCanonicalFileName: GetCanonicalFileName): boolean { + const canonicalFileName = getCanonicalFileName(fileName); + const canonicalDirectoryName = getCanonicalFileName(directoryName); + return startsWith(canonicalFileName, canonicalDirectoryName + "/") || startsWith(canonicalFileName, canonicalDirectoryName + "\\"); + } + + //// Relative Paths + + export function getPathComponentsRelativeTo(from: string, to: string, stringEqualityComparer: (a: string, b: string) => boolean, getCanonicalFileName: GetCanonicalFileName) { + const fromComponents = reducePathComponents(getPathComponents(from)); + const toComponents = reducePathComponents(getPathComponents(to)); + + let start: number; + for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { + const fromComponent = getCanonicalFileName(fromComponents[start]); + const toComponent = getCanonicalFileName(toComponents[start]); + const comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; + if (!comparer(fromComponent, toComponent)) break; + } + + if (start === 0) { + return toComponents; + } + + const components = toComponents.slice(start); + const relative: string[] = []; + for (; start < fromComponents.length; start++) { + relative.push(".."); + } + return ["", ...relative, ...components]; + } + + /** + * Gets a relative path that can be used to traverse between `from` and `to`. + */ + export function getRelativePathFromDirectory(from: string, to: string, ignoreCase: boolean): string; + /** + * Gets a relative path that can be used to traverse between `from` and `to`. + */ + export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileName: GetCanonicalFileName): string; // eslint-disable-line @typescript-eslint/unified-signatures + export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileNameOrIgnoreCase: GetCanonicalFileName | boolean) { + Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); + const getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity; + const ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; + const pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName); + return getPathFromPathComponents(pathComponents); + } + + export function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string { + return !isRootedDiskPath(absoluteOrRelativePath) + ? absoluteOrRelativePath + : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); + } + + export function getRelativePathFromFile(from: string, to: string, getCanonicalFileName: GetCanonicalFileName) { + return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); + } + + export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, isAbsolutePathAnUrl: boolean) { + const pathComponents = getPathComponentsRelativeTo( + resolvePath(currentDirectory, directoryPathOrUrl), + resolvePath(currentDirectory, relativeOrAbsolutePath), + equateStringsCaseSensitive, + getCanonicalFileName + ); + + const firstComponent = pathComponents[0]; + if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { + const prefix = firstComponent.charAt(0) === directorySeparator ? "file://" : "file:///"; + pathComponents[0] = prefix + firstComponent; + } + + return getPathFromPathComponents(pathComponents); + } + + //// Path Traversal + + /** + * Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. + */ + export function forEachAncestorDirectory(directory: Path, callback: (directory: Path) => T | undefined): T | undefined; + export function forEachAncestorDirectory(directory: string, callback: (directory: string) => T | undefined): T | undefined; + export function forEachAncestorDirectory(directory: Path, callback: (directory: Path) => T | undefined): T | undefined { + while (true) { + const result = callback(directory); + if (result !== undefined) { + return result; + } + + const parentPath = getDirectoryPath(directory); + if (parentPath === directory) { + return undefined; + } + + directory = parentPath; + } + } +} \ No newline at end of file diff --git a/src/compiler/perfLogger.ts b/src/compiler/perfLogger.ts index 5d7b1dae122..8ed8feac90c 100644 --- a/src/compiler/perfLogger.ts +++ b/src/compiler/perfLogger.ts @@ -38,6 +38,4 @@ namespace ts { /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */ export const perfLogger: PerfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger; - const args = typeof process === "undefined" ? [] : process.argv; - perfLogger.logInfoEvent(`Starting TypeScript v${versionMajorMinor} with command line: ${JSON.stringify(args)}`); } diff --git a/src/compiler/program.ts b/src/compiler/program.ts index f81d007141b..0c8444daa2f 100644 --- a/src/compiler/program.ts +++ b/src/compiler/program.ts @@ -545,6 +545,9 @@ namespace ts { return resolutions; } + /* @internal */ + export const inferredTypesContainingFile = "__inferred type names__.ts"; + interface DiagnosticCache { perFile?: Map; allDiagnostics?: Diagnostic[]; @@ -875,7 +878,7 @@ namespace ts { if (typeReferences.length) { // This containingFilename needs to match with the one used in managed-side const containingDirectory = options.configFilePath ? getDirectoryPath(options.configFilePath) : host.getCurrentDirectory(); - const containingFilename = combinePaths(containingDirectory, "__inferred type names__.ts"); + const containingFilename = combinePaths(containingDirectory, inferredTypesContainingFile); const resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename); for (let i = 0; i < typeReferences.length; i++) { processTypeReferenceDirective(typeReferences[i], resolutions[i]); @@ -2926,10 +2929,6 @@ namespace ts { programDiagnostics.add(createCompilerDiagnostic(Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified)); } - if (options.noEmit && isIncrementalCompilation(options)) { - createDiagnosticForOptionName(Diagnostics.Option_0_cannot_be_specified_with_option_1, "noEmit", options.incremental ? "incremental" : "composite"); - } - verifyProjectReferences(); // List of collected files is complete; validate exhautiveness if this is a project with a file list diff --git a/src/compiler/resolutionCache.ts b/src/compiler/resolutionCache.ts index 49f1fd26bc3..5af7919b6d6 100644 --- a/src/compiler/resolutionCache.ts +++ b/src/compiler/resolutionCache.ts @@ -669,6 +669,11 @@ namespace ts { // Mark the file as needing re-evaluation of module resolution instead of using it blindly. resolution.isInvalidated = true; (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = createMap())).set(containingFilePath, true); + + // When its a file with inferred types resolution, invalidate type reference directive resolution + if (containingFilePath.endsWith(inferredTypesContainingFile)) { + resolutionHost.onChangedAutomaticTypeDirectiveNames(); + } } }); }); diff --git a/src/compiler/sys.ts b/src/compiler/sys.ts index 1304ab19349..ad866cba130 100644 --- a/src/compiler/sys.ts +++ b/src/compiler/sys.ts @@ -682,6 +682,7 @@ namespace ts { /*@internal*/ bufferFrom?(input: string, encoding?: string): Buffer; // For testing /*@internal*/ now?(): Date; + /*@internal*/ require?(baseDir: string, moduleName: string): RequireResult; } export interface FileWatcher { @@ -876,6 +877,15 @@ namespace ts { bufferFrom, base64decode: input => bufferFrom(input, "base64").toString("utf8"), base64encode: input => bufferFrom(input).toString("base64"), + require: (baseDir, moduleName) => { + try { + const modulePath = resolveJSModule(moduleName, baseDir, nodeSystem); + return { module: require(modulePath), modulePath, error: undefined }; + } + catch (error) { + return { module: undefined, modulePath: undefined, error }; + } + } }; return nodeSystem; @@ -1022,6 +1032,7 @@ namespace ts { return watchDirectoryUsingFsWatch; } + // defer watchDirectoryRecursively as it depends on `ts.createMap()` which may not be usable yet. const watchDirectory = tscWatchDirectory === "RecursiveDirectoryUsingFsWatchFile" ? createWatchDirectoryUsing(fsWatchFile) : tscWatchDirectory === "RecursiveDirectoryUsingDynamicPriorityPolling" ? diff --git a/src/compiler/transformers/classFields.ts b/src/compiler/transformers/classFields.ts index 1424d293369..b3e59860888 100644 --- a/src/compiler/transformers/classFields.ts +++ b/src/compiler/transformers/classFields.ts @@ -132,7 +132,7 @@ namespace ts { // Create a temporary variable to store a computed property name (if necessary). // If it's not inlineable, then we emit an expression after the class which assigns // the property name to the temporary variable. - const expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer); + const expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields); if (expr && !isSimpleInlineableExpression(expr)) { (pendingExpressions || (pendingExpressions = [])).push(expr); } @@ -145,7 +145,7 @@ namespace ts { } const savedPendingExpressions = pendingExpressions; - pendingExpressions = undefined!; + pendingExpressions = undefined; const extendsClauseElement = getEffectiveBaseTypeNode(node); const isDerivedClass = !!(extendsClauseElement && skipOuterExpressions(extendsClauseElement.expression).kind !== SyntaxKind.NullKeyword); diff --git a/src/compiler/transformers/declarations.ts b/src/compiler/transformers/declarations.ts index 1c6bd16e1ba..7746ad00b43 100644 --- a/src/compiler/transformers/declarations.ts +++ b/src/compiler/transformers/declarations.ts @@ -285,6 +285,7 @@ namespace ts { let combinedStatements: NodeArray; if (isSourceFileJS(currentSourceFile)) { combinedStatements = createNodeArray(transformDeclarationsForJS(node)); + refs.forEach(referenceVisitor); emittedImports = filter(combinedStatements, isAnyImportSyntax); } else { diff --git a/src/compiler/tsbuild.ts b/src/compiler/tsbuild.ts index aea85d1fb17..1924be4df89 100644 --- a/src/compiler/tsbuild.ts +++ b/src/compiler/tsbuild.ts @@ -1788,31 +1788,25 @@ namespace ts { let reportQueue = true; let successfulProjects = 0; - let errorProjects = 0; while (true) { const invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue); if (!invalidatedProject) break; reportQueue = false; invalidatedProject.done(cancellationToken); - if (state.diagnostics.has(invalidatedProject.projectPath)) { - errorProjects++; - } - else { - successfulProjects++; - } + if (!state.diagnostics.has(invalidatedProject.projectPath)) successfulProjects++; } disableCache(state); reportErrorSummary(state, buildOrder); startWatching(state, buildOrder); - return isCircularBuildOrder(buildOrder) ? - ExitStatus.ProjectReferenceCycle_OutputsSkupped : - errorProjects ? - successfulProjects ? - ExitStatus.DiagnosticsPresent_OutputsGenerated : - ExitStatus.DiagnosticsPresent_OutputsSkipped : - ExitStatus.Success; + return isCircularBuildOrder(buildOrder) + ? ExitStatus.ProjectReferenceCycle_OutputsSkipped + : !buildOrder.some(p => state.diagnostics.has(toResolvedConfigFilePath(state, p))) + ? ExitStatus.Success + : successfulProjects + ? ExitStatus.DiagnosticsPresent_OutputsGenerated + : ExitStatus.DiagnosticsPresent_OutputsSkipped; } function clean(state: SolutionBuilderState, project?: string, onlyReferences?: boolean) { @@ -1821,7 +1815,7 @@ namespace ts { if (isCircularBuildOrder(buildOrder)) { reportErrors(state, buildOrder.circularDiagnostics); - return ExitStatus.ProjectReferenceCycle_OutputsSkupped; + return ExitStatus.ProjectReferenceCycle_OutputsSkipped; } const { options, host } = state; diff --git a/src/compiler/tsconfig.json b/src/compiler/tsconfig.json index c90c6f35b34..cef7aba0484 100644 --- a/src/compiler/tsconfig.json +++ b/src/compiler/tsconfig.json @@ -4,7 +4,9 @@ "outFile": "../../built/local/compiler.js" }, - "references": [], + "references": [ + { "path": "../shims" }, + ], "files": [ "core.ts", @@ -15,6 +17,7 @@ "types.ts", "sys.ts", + "path.ts", "diagnosticInformationMap.generated.ts", "scanner.ts", "utilities.ts", diff --git a/src/compiler/tsconfig.release.json b/src/compiler/tsconfig.release.json index 39ffc791393..5ddd6d8e3a3 100644 --- a/src/compiler/tsconfig.release.json +++ b/src/compiler/tsconfig.release.json @@ -4,5 +4,8 @@ "outFile": "../../built/local/compiler.release.js", "removeComments": true, "preserveConstEnums": false - } + }, + "references": [ + { "path": "../shims" } + ] } diff --git a/src/compiler/types.ts b/src/compiler/types.ts index 64415c08d2e..25ed46dde55 100644 --- a/src/compiler/types.ts +++ b/src/compiler/types.ts @@ -2250,12 +2250,14 @@ namespace ts { parent: CaseBlock; expression: Expression; statements: NodeArray; + /* @internal */ fallthroughFlowNode?: FlowNode; } export interface DefaultClause extends Node { kind: SyntaxKind.DefaultClause; parent: CaseBlock; statements: NodeArray; + /* @internal */ fallthroughFlowNode?: FlowNode; } export type CaseOrDefaultClause = CaseClause | DefaultClause; @@ -2681,6 +2683,7 @@ namespace ts { isArrayType?: boolean; } + // NOTE: Ensure this is up-to-date with src/debug/debug.ts export const enum FlowFlags { Unreachable = 1 << 0, // Unreachable code Start = 1 << 1, // Start of flow graph @@ -3258,6 +3261,9 @@ namespace ts { InvalidProject_OutputsSkipped = 3, // When build is skipped because project references form cycle + ProjectReferenceCycle_OutputsSkipped = 4, + + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ProjectReferenceCycle_OutputsSkupped = 4, } @@ -3365,8 +3371,10 @@ namespace ts { getFullyQualifiedName(symbol: Symbol): string; getAugmentedPropertiesOfType(type: Type): Symbol[]; + getRootSymbols(symbol: Symbol): readonly Symbol[]; getContextualType(node: Expression): Type | undefined; + /* @internal */ getContextualType(node: Expression, contextFlags?: ContextFlags): Type | undefined; // eslint-disable-line @typescript-eslint/unified-signatures /* @internal */ getContextualTypeForObjectLiteralElement(element: ObjectLiteralElementLike): Type | undefined; /* @internal */ getContextualTypeForArgumentAtIndex(call: CallLikeExpression, argIndex: number): Type | undefined; /* @internal */ getContextualTypeForJsxAttribute(attribute: JsxAttribute | JsxSpreadAttribute): Type | undefined; @@ -3443,8 +3451,7 @@ namespace ts { resolvedReturnType: Type, typePredicate: TypePredicate | undefined, minArgumentCount: number, - hasRestParameter: boolean, - hasLiteralTypes: boolean, + flags: SignatureFlags ): Signature; /* @internal */ createSymbol(flags: SymbolFlags, name: __String): TransientSymbol; /* @internal */ createIndexInfo(type: Type, isReadonly: boolean, declaration?: SignatureDeclaration): IndexInfo; @@ -3526,6 +3533,14 @@ namespace ts { Subtype } + /* @internal */ + export const enum ContextFlags { + None = 0, + Signature = 1 << 0, // Obtaining contextual signature + NoConstraints = 1 << 1, // Don't obtain type variable constraints + Completion = 1 << 2, // Obtaining constraint type for completion + } + // NOTE: If modifying this enum, must modify `TypeFormatFlags` too! export const enum NodeBuilderFlags { None = 0, @@ -4655,7 +4670,22 @@ namespace ts { Construct, } + /* @internal */ + export const enum SignatureFlags { + None = 0, + HasRestParameter = 1 << 0, // Indicates last parameter is rest parameter + HasLiteralTypes = 1 << 1, // Indicates signature is specialized + IsOptionalCall = 1 << 2, // Indicates signature comes from a CallChain + + // We do not propagate `IsOptionalCall` to instantiated signatures, as that would result in us + // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when + // instantiating the return type. + PropagatingFlags = HasRestParameter | HasLiteralTypes, + } + export interface Signature { + /* @internal */ flags: SignatureFlags; + /* @internal */ checker?: TypeChecker; declaration?: SignatureDeclaration | JSDocSignature; // Originating declaration typeParameters?: readonly TypeParameter[]; // Type parameters (undefined if non-generic) parameters: readonly Symbol[]; // Parameters @@ -4672,10 +4702,6 @@ namespace ts { /* @internal */ minArgumentCount: number; // Number of non-optional parameters /* @internal */ - hasRestParameter: boolean; // True if last parameter is rest parameter - /* @internal */ - hasLiteralTypes: boolean; // True if specialized - /* @internal */ target?: Signature; // Instantiation target /* @internal */ mapper?: TypeMapper; // Instantiation mapper @@ -4686,11 +4712,11 @@ namespace ts { /* @internal */ canonicalSignatureCache?: Signature; // Canonical version of signature (deferred) /* @internal */ + optionalCallSignatureCache?: Signature; // Optional chained call version of signature (deferred) + /* @internal */ isolatedSignatureType?: ObjectType; // A manufactured type that just contains the signature for purposes of signature comparison /* @internal */ instantiations?: Map; // Generic signature instantiation cache - /* @internal */ - isOptionalCall?: boolean; } export const enum IndexKind { @@ -4935,6 +4961,7 @@ namespace ts { lib?: string[]; /*@internal*/listEmittedFiles?: boolean; /*@internal*/listFiles?: boolean; + /*@internal*/listFilesOnly?: boolean; locale?: string; mapRoot?: string; maxNodeModuleJsDepth?: number; @@ -5123,6 +5150,11 @@ namespace ts { /* @internal */ spec: ConfigFileSpecs; } + /* @internal */ + export type RequireResult = + | { module: T, modulePath?: string, error: undefined } + | { module: undefined, modulePath?: undefined, error: { stack?: string, message?: string } }; + export interface CreateProgramOptions { rootNames: readonly string[]; options: CompilerOptions; @@ -6149,6 +6181,8 @@ namespace ts { readFile?(path: string): string | undefined; /* @internal */ getProbableSymlinks?(files: readonly SourceFile[]): ReadonlyMap; + /* @internal */ + getGlobalTypingsCacheLocation?(): string | undefined; } // Note: this used to be deprecated in our public API, but is still used internally @@ -6418,6 +6452,7 @@ namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.ts index 00447edd42a..8733d07c952 100644 --- a/src/compiler/utilities.ts +++ b/src/compiler/utilities.ts @@ -36,7 +36,7 @@ namespace ts { /** Create a new escaped identifier map. */ export function createUnderscoreEscapedMap(): UnderscoreEscapedMap { - return new MapCtr() as UnderscoreEscapedMap; + return new Map() as UnderscoreEscapedMap; } export function hasEntries(map: ReadonlyUnderscoreEscapedMap | undefined): map is ReadonlyUnderscoreEscapedMap { @@ -94,13 +94,6 @@ namespace ts { }; } - export function toPath(fileName: string, basePath: string | undefined, getCanonicalFileName: (path: string) => string): Path { - const nonCanonicalizedPath = isRootedDiskPath(fileName) - ? normalizePath(fileName) - : getNormalizedAbsolutePath(fileName, basePath); - return getCanonicalFileName(nonCanonicalizedPath); - } - export function changesAffectModuleResolution(oldOptions: CompilerOptions, newOptions: CompilerOptions): boolean { return oldOptions.configFilePath !== newOptions.configFilePath || optionsHaveModuleResolutionChanges(oldOptions, newOptions); @@ -968,6 +961,11 @@ namespace ts { break; case SyntaxKind.ArrowFunction: return getErrorSpanForArrowFunction(sourceFile, node); + case SyntaxKind.CaseClause: + case SyntaxKind.DefaultClause: + const start = skipTrivia(sourceFile.text, (node).pos); + const end = (node).statements.length > 0 ? (node).statements[0].pos : (node).end; + return createTextSpanFromBounds(start, end); } if (errorNode === undefined) { @@ -1821,9 +1819,9 @@ namespace ts { * exactly one argument (of the form 'require("name")'). * This function does not test if the node is in a JavaScript file or not. */ - export function isRequireCall(callExpression: Node, checkArgumentIsStringLiteralLike: true): callExpression is RequireOrImportCall & { expression: Identifier, arguments: [StringLiteralLike] }; - export function isRequireCall(callExpression: Node, checkArgumentIsStringLiteralLike: boolean): callExpression is CallExpression; - export function isRequireCall(callExpression: Node, checkArgumentIsStringLiteralLike: boolean): callExpression is CallExpression { + export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgument: true): callExpression is RequireOrImportCall & { expression: Identifier, arguments: [StringLiteralLike] }; + export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgument: boolean): callExpression is CallExpression; + export function isRequireCall(callExpression: Node, requireStringLiteralLikeArgument: boolean): callExpression is CallExpression { if (callExpression.kind !== SyntaxKind.CallExpression) { return false; } @@ -1837,7 +1835,7 @@ namespace ts { return false; } const arg = args[0]; - return !checkArgumentIsStringLiteralLike || isStringLiteralLike(arg); + return !requireStringLiteralLikeArgument || isStringLiteralLike(arg); } export function isSingleOrDoubleQuote(charCode: number) { @@ -2060,7 +2058,7 @@ namespace ts { idText(expr.expression.expression) === "Object" && idText(expr.expression.name) === "defineProperty" && isStringOrNumericLiteralLike(expr.arguments[1]) && - isBindableStaticNameExpression(expr.arguments[0]); + isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true); } export function isBindableStaticElementAccessExpression(node: Node, excludeThisKeyword?: boolean): node is BindableStaticElementAccessExpression { @@ -2174,9 +2172,11 @@ namespace ts { nextToLast = nextToLast.expression as Exclude; } const id = nextToLast.expression; - if (id.escapedText === "exports" || - id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") { - // exports.name = expr OR module.exports.name = expr + if ((id.escapedText === "exports" || + id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") && + // ExportsProperty does not support binding with computed names + isBindableStaticAccessExpression(lhs)) { + // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ... return AssignmentDeclarationKind.ExportsProperty; } // F.G...x = expr @@ -4179,6 +4179,23 @@ namespace ts { return node.kind === SyntaxKind.Identifier || isPropertyAccessEntityNameExpression(node); } + export function getFirstIdentifier(node: EntityNameOrEntityNameExpression): Identifier { + switch (node.kind) { + case SyntaxKind.Identifier: + return node; + case SyntaxKind.QualifiedName: + do { + node = node.left; + } while (node.kind !== SyntaxKind.Identifier); + return node; + case SyntaxKind.PropertyAccessExpression: + do { + node = node.expression; + } while (node.kind !== SyntaxKind.Identifier); + return node; + } + } + export function isDottedName(node: Expression): boolean { return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.ThisKeyword || node.kind === SyntaxKind.PropertyAccessExpression && isDottedName((node).expression) || @@ -4733,25 +4750,6 @@ namespace ts { }); } - /** Calls `callback` on `directory` and every ancestor directory it has, returning the first defined result. */ - export function forEachAncestorDirectory(directory: Path, callback: (directory: Path) => T | undefined): T | undefined; - export function forEachAncestorDirectory(directory: string, callback: (directory: string) => T | undefined): T | undefined; - export function forEachAncestorDirectory(directory: Path, callback: (directory: Path) => T | undefined): T | undefined { - while (true) { - const result = callback(directory); - if (result !== undefined) { - return result; - } - - const parentPath = getDirectoryPath(directory); - if (parentPath === directory) { - return undefined; - } - - directory = parentPath; - } - } - // Return true if the given type is the constructor type for an abstract class export function isAbstractConstructorType(type: Type): boolean { return !!(getObjectFlags(type) & ObjectFlags.Anonymous) && !!type.symbol && isAbstractConstructorSymbol(type.symbol); @@ -5906,9 +5904,19 @@ namespace ts { } export function isOptionalChain(node: Node): node is PropertyAccessChain | ElementAccessChain | CallChain { - return isPropertyAccessChain(node) - || isElementAccessChain(node) - || isCallChain(node); + const kind = node.kind; + return !!(node.flags & NodeFlags.OptionalChain) && + (kind === SyntaxKind.PropertyAccessExpression + || kind === SyntaxKind.ElementAccessExpression + || kind === SyntaxKind.CallExpression); + } + + /** + * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`). + */ + /* @internal */ + export function isExpressionOfOptionalChainRoot(node: Node): node is Expression & { parent: OptionalChainRoot } { + return isOptionalChainRoot(node.parent) && node.parent.expression === node; } export function isNewExpression(node: Node): node is NewExpression { @@ -7310,7 +7318,7 @@ namespace ts { getSourceFileConstructor(): new (kind: SyntaxKind.SourceFile, pos?: number, end?: number) => SourceFile; getSymbolConstructor(): new (flags: SymbolFlags, name: __String) => Symbol; getTypeConstructor(): new (checker: TypeChecker, flags: TypeFlags) => Type; - getSignatureConstructor(): new (checker: TypeChecker) => Signature; + getSignatureConstructor(): new (checker: TypeChecker, flags: SignatureFlags) => Signature; getSourceMapSourceConstructor(): new (fileName: string, text: string, skipTrivia?: (pos: number) => number) => SourceMapSource; } @@ -7331,7 +7339,12 @@ namespace ts { } } - function Signature() {} + function Signature(this: Signature, checker: TypeChecker, flags: SignatureFlags) { + this.flags = flags; + if (Debug.isDebugging) { + this.checker = checker; + } + } function Node(this: Node, kind: SyntaxKind, pos: number, end: number) { this.pos = pos; @@ -7635,294 +7648,6 @@ namespace ts { return true; } - /** - * Internally, we represent paths as strings with '/' as the directory separator. - * When we make system calls (eg: LanguageServiceHost.getDirectory()), - * we expect the host to correctly handle paths in our specified format. - */ - export const directorySeparator = "/"; - const altDirectorySeparator = "\\"; - const urlSchemeSeparator = "://"; - const backslashRegExp = /\\/g; - - /** - * Normalize path separators. - */ - export function normalizeSlashes(path: string): string { - return path.replace(backslashRegExp, directorySeparator); - } - - function isVolumeCharacter(charCode: number) { - return (charCode >= CharacterCodes.a && charCode <= CharacterCodes.z) || - (charCode >= CharacterCodes.A && charCode <= CharacterCodes.Z); - } - - function getFileUrlVolumeSeparatorEnd(url: string, start: number) { - const ch0 = url.charCodeAt(start); - if (ch0 === CharacterCodes.colon) return start + 1; - if (ch0 === CharacterCodes.percent && url.charCodeAt(start + 1) === CharacterCodes._3) { - const ch2 = url.charCodeAt(start + 2); - if (ch2 === CharacterCodes.a || ch2 === CharacterCodes.A) return start + 3; - } - return -1; - } - - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * If the root is part of a URL, the twos-complement of the root length is returned. - */ - function getEncodedRootLength(path: string): number { - if (!path) return 0; - const ch0 = path.charCodeAt(0); - - // POSIX or UNC - if (ch0 === CharacterCodes.slash || ch0 === CharacterCodes.backslash) { - if (path.charCodeAt(1) !== ch0) return 1; // POSIX: "/" (or non-normalized "\") - - const p1 = path.indexOf(ch0 === CharacterCodes.slash ? directorySeparator : altDirectorySeparator, 2); - if (p1 < 0) return path.length; // UNC: "//server" or "\\server" - - return p1 + 1; // UNC: "//server/" or "\\server\" - } - - // DOS - if (isVolumeCharacter(ch0) && path.charCodeAt(1) === CharacterCodes.colon) { - const ch2 = path.charCodeAt(2); - if (ch2 === CharacterCodes.slash || ch2 === CharacterCodes.backslash) return 3; // DOS: "c:/" or "c:\" - if (path.length === 2) return 2; // DOS: "c:" (but not "c:d") - } - - // URL - const schemeEnd = path.indexOf(urlSchemeSeparator); - if (schemeEnd !== -1) { - const authorityStart = schemeEnd + urlSchemeSeparator.length; - const authorityEnd = path.indexOf(directorySeparator, authorityStart); - if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path" - // For local "file" URLs, include the leading DOS volume (if present). - // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a - // special case interpreted as "the machine from which the URL is being interpreted". - const scheme = path.slice(0, schemeEnd); - const authority = path.slice(authorityStart, authorityEnd); - if (scheme === "file" && (authority === "" || authority === "localhost") && - isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) { - const volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2); - if (volumeSeparatorEnd !== -1) { - if (path.charCodeAt(volumeSeparatorEnd) === CharacterCodes.slash) { - // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/" - return ~(volumeSeparatorEnd + 1); - } - if (volumeSeparatorEnd === path.length) { - // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a" - // but not "file:///c:d" or "file:///c%3ad" - return ~volumeSeparatorEnd; - } - } - } - return ~(authorityEnd + 1); // URL: "file://server/", "http://server/" - } - return ~path.length; // URL: "file://server", "http://server" - } - - // relative - return 0; - } - - /** - * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files"). - * - * For example: - * ```ts - * getRootLength("a") === 0 // "" - * getRootLength("/") === 1 // "/" - * getRootLength("c:") === 2 // "c:" - * getRootLength("c:d") === 0 // "" - * getRootLength("c:/") === 3 // "c:/" - * getRootLength("c:\\") === 3 // "c:\\" - * getRootLength("//server") === 7 // "//server" - * getRootLength("//server/share") === 8 // "//server/" - * getRootLength("\\\\server") === 7 // "\\\\server" - * getRootLength("\\\\server\\share") === 8 // "\\\\server\\" - * getRootLength("file:///path") === 8 // "file:///" - * getRootLength("file:///c:") === 10 // "file:///c:" - * getRootLength("file:///c:d") === 8 // "file:///" - * getRootLength("file:///c:/path") === 11 // "file:///c:/" - * getRootLength("file://server") === 13 // "file://server" - * getRootLength("file://server/path") === 14 // "file://server/" - * getRootLength("http://server") === 13 // "http://server" - * getRootLength("http://server/path") === 14 // "http://server/" - * ``` - */ - export function getRootLength(path: string) { - const rootLength = getEncodedRootLength(path); - return rootLength < 0 ? ~rootLength : rootLength; - } - - // TODO(rbuckton): replace references with `resolvePath` - export function normalizePath(path: string): string { - return resolvePath(path); - } - - export function normalizePathAndParts(path: string): { path: string, parts: string[] } { - path = normalizeSlashes(path); - const [root, ...parts] = reducePathComponents(getPathComponents(path)); - if (parts.length) { - const joinedParts = root + parts.join(directorySeparator); - return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts }; - } - else { - return { path: root, parts }; - } - } - - /** - * Returns the path except for its basename. Semantics align with NodeJS's `path.dirname` - * except that we support URLs as well. - * - * ```ts - * getDirectoryPath("/path/to/file.ext") === "/path/to" - * getDirectoryPath("/path/to/") === "/path" - * getDirectoryPath("/") === "/" - * ``` - */ - export function getDirectoryPath(path: Path): Path; - /** - * Returns the path except for its basename. Semantics align with NodeJS's `path.dirname` - * except that we support URLs as well. - * - * ```ts - * getDirectoryPath("/path/to/file.ext") === "/path/to" - * getDirectoryPath("/path/to/") === "/path" - * getDirectoryPath("/") === "/" - * ``` - */ - export function getDirectoryPath(path: string): string; - export function getDirectoryPath(path: string): string { - path = normalizeSlashes(path); - - // If the path provided is itself the root, then return it. - const rootLength = getRootLength(path); - if (rootLength === path.length) return path; - - // return the leading portion of the path up to the last (non-terminal) directory separator - // but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - return path.slice(0, Math.max(rootLength, path.lastIndexOf(directorySeparator))); - } - - export function startsWithDirectory(fileName: string, directoryName: string, getCanonicalFileName: GetCanonicalFileName): boolean { - const canonicalFileName = getCanonicalFileName(fileName); - const canonicalDirectoryName = getCanonicalFileName(directoryName); - return startsWith(canonicalFileName, canonicalDirectoryName + "/") || startsWith(canonicalFileName, canonicalDirectoryName + "\\"); - } - - export function isUrl(path: string) { - return getEncodedRootLength(path) < 0; - } - - export function pathIsRelative(path: string): boolean { - return /^\.\.?($|[\\/])/.test(path); - } - - /** - * Determines whether a path is an absolute path (e.g. starts with `/`, or a dos path - * like `c:`, `c:\` or `c:/`). - */ - export function isRootedDiskPath(path: string) { - return getEncodedRootLength(path) > 0; - } - - /** - * Determines whether a path consists only of a path root. - */ - export function isDiskPathRoot(path: string) { - const rootLength = getEncodedRootLength(path); - return rootLength > 0 && rootLength === path.length; - } - - export function convertToRelativePath(absoluteOrRelativePath: string, basePath: string, getCanonicalFileName: (path: string) => string): string { - return !isRootedDiskPath(absoluteOrRelativePath) - ? absoluteOrRelativePath - : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false); - } - - function pathComponents(path: string, rootLength: number) { - const root = path.substring(0, rootLength); - const rest = path.substring(rootLength).split(directorySeparator); - if (rest.length && !lastOrUndefined(rest)) rest.pop(); - return [root, ...rest]; - } - - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is not normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - export function getPathComponents(path: string, currentDirectory = "") { - path = combinePaths(currentDirectory, path); - const rootLength = getRootLength(path); - return pathComponents(path, rootLength); - } - - /** - * Reduce an array of path components to a more simplified path by navigating any - * `"."` or `".."` entries in the path. - */ - export function reducePathComponents(components: readonly string[]) { - if (!some(components)) return []; - const reduced = [components[0]]; - for (let i = 1; i < components.length; i++) { - const component = components[i]; - if (!component) continue; - if (component === ".") continue; - if (component === "..") { - if (reduced.length > 1) { - if (reduced[reduced.length - 1] !== "..") { - reduced.pop(); - continue; - } - } - else if (reduced[0]) continue; - } - reduced.push(component); - } - return reduced; - } - - /** - * Parse a path into an array containing a root component (at index 0) and zero or more path - * components (at indices > 0). The result is normalized. - * If the path is relative, the root component is `""`. - * If the path is absolute, the root component includes the first path separator (`/`). - */ - export function getNormalizedPathComponents(path: string, currentDirectory: string | undefined) { - return reducePathComponents(getPathComponents(path, currentDirectory)); - } - - export function getNormalizedAbsolutePath(fileName: string, currentDirectory: string | undefined) { - return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory)); - } - - /** - * Formats a parsed path consisting of a root component (at index 0) and zero or more path - * segments (at indices > 0). - */ - export function getPathFromPathComponents(pathComponents: readonly string[]) { - if (pathComponents.length === 0) return ""; - - const root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]); - return root + pathComponents.slice(1).join(directorySeparator); - } - - export function getNormalizedAbsolutePathWithoutRoot(fileName: string, currentDirectory: string | undefined) { - return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory)); - } - - function getPathWithoutRoot(pathComponents: readonly string[]) { - if (pathComponents.length === 0) return ""; - return pathComponents.slice(1).join(directorySeparator); - } - export function discoverProbableSymlinks(files: readonly SourceFile[], getCanonicalFileName: GetCanonicalFileName, cwd: string): ReadonlyMap { const result = createMap(); const symlinks = flatten(mapDefined(files, sf => @@ -7956,278 +7681,8 @@ namespace ts { /* @internal */ namespace ts { - export function getPathComponentsRelativeTo(from: string, to: string, stringEqualityComparer: (a: string, b: string) => boolean, getCanonicalFileName: GetCanonicalFileName) { - const fromComponents = reducePathComponents(getPathComponents(from)); - const toComponents = reducePathComponents(getPathComponents(to)); - - let start: number; - for (start = 0; start < fromComponents.length && start < toComponents.length; start++) { - const fromComponent = getCanonicalFileName(fromComponents[start]); - const toComponent = getCanonicalFileName(toComponents[start]); - const comparer = start === 0 ? equateStringsCaseInsensitive : stringEqualityComparer; - if (!comparer(fromComponent, toComponent)) break; - } - - if (start === 0) { - return toComponents; - } - - const components = toComponents.slice(start); - const relative: string[] = []; - for (; start < fromComponents.length; start++) { - relative.push(".."); - } - return ["", ...relative, ...components]; - } - - export function getRelativePathFromFile(from: string, to: string, getCanonicalFileName: GetCanonicalFileName) { - return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName)); - } - - /** - * Gets a relative path that can be used to traverse between `from` and `to`. - */ - export function getRelativePathFromDirectory(from: string, to: string, ignoreCase: boolean): string; - /** - * Gets a relative path that can be used to traverse between `from` and `to`. - */ - export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileName: GetCanonicalFileName): string; // eslint-disable-line @typescript-eslint/unified-signatures - export function getRelativePathFromDirectory(fromDirectory: string, to: string, getCanonicalFileNameOrIgnoreCase: GetCanonicalFileName | boolean) { - Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative"); - const getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : identity; - const ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false; - const pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive, getCanonicalFileName); - return getPathFromPathComponents(pathComponents); - } - - export function getRelativePathToDirectoryOrUrl(directoryPathOrUrl: string, relativeOrAbsolutePath: string, currentDirectory: string, getCanonicalFileName: GetCanonicalFileName, isAbsolutePathAnUrl: boolean) { - const pathComponents = getPathComponentsRelativeTo( - resolvePath(currentDirectory, directoryPathOrUrl), - resolvePath(currentDirectory, relativeOrAbsolutePath), - equateStringsCaseSensitive, - getCanonicalFileName - ); - - const firstComponent = pathComponents[0]; - if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) { - const prefix = firstComponent.charAt(0) === directorySeparator ? "file://" : "file:///"; - pathComponents[0] = prefix + firstComponent; - } - - return getPathFromPathComponents(pathComponents); - } - - /** - * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed - * with `./` or `../`) so as not to be confused with an unprefixed module name. - */ - export function ensurePathIsNonModuleName(path: string): string { - return getRootLength(path) === 0 && !pathIsRelative(path) ? "./" + path : path; - } - - /** - * Returns the path except for its containing directory name. - * Semantics align with NodeJS's `path.basename` except that we support URL's as well. - * - * ```ts - * getBaseFileName("/path/to/file.ext") === "file.ext" - * getBaseFileName("/path/to/") === "to" - * getBaseFileName("/") === "" - * ``` - */ - export function getBaseFileName(path: string): string; - /** - * Gets the portion of a path following the last (non-terminal) separator (`/`). - * Semantics align with NodeJS's `path.basename` except that we support URL's as well. - * If the base name has any one of the provided extensions, it is removed. - * - * ```ts - * getBaseFileName("/path/to/file.ext", ".ext", true) === "file" - * getBaseFileName("/path/to/file.js", ".ext", true) === "file.js" - * ``` - */ - export function getBaseFileName(path: string, extensions: string | readonly string[], ignoreCase: boolean): string; - export function getBaseFileName(path: string, extensions?: string | readonly string[], ignoreCase?: boolean) { - path = normalizeSlashes(path); - - // if the path provided is itself the root, then it has not file name. - const rootLength = getRootLength(path); - if (rootLength === path.length) return ""; - - // return the trailing portion of the path starting after the last (non-terminal) directory - // separator but not including any trailing directory separator. - path = removeTrailingDirectorySeparator(path); - const name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(directorySeparator) + 1)); - const extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined; - return extension ? name.slice(0, name.length - extension.length) : name; - } - - /** - * Combines paths. If a path is absolute, it replaces any previous path. - */ - export function combinePaths(path: string, ...paths: (string | undefined)[]): string { - if (path) path = normalizeSlashes(path); - for (let relativePath of paths) { - if (!relativePath) continue; - relativePath = normalizeSlashes(relativePath); - if (!path || getRootLength(relativePath) !== 0) { - path = relativePath; - } - else { - path = ensureTrailingDirectorySeparator(path) + relativePath; - } - } - return path; - } - - /** - * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any - * `.` and `..` path components are resolved. - */ - export function resolvePath(path: string, ...paths: (string | undefined)[]): string { - const combined = some(paths) ? combinePaths(path, ...paths) : normalizeSlashes(path); - const normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(combined))); - return normalized && hasTrailingDirectorySeparator(combined) ? ensureTrailingDirectorySeparator(normalized) : normalized; - } - - /** - * Determines whether a path has a trailing separator (`/` or `\\`). - */ - export function hasTrailingDirectorySeparator(path: string) { - if (path.length === 0) return false; - const ch = path.charCodeAt(path.length - 1); - return ch === CharacterCodes.slash || ch === CharacterCodes.backslash; - } - - /** - * Removes a trailing directory separator from a path. - * @param path The path. - */ - export function removeTrailingDirectorySeparator(path: Path): Path; - export function removeTrailingDirectorySeparator(path: string): string; - export function removeTrailingDirectorySeparator(path: string) { - if (hasTrailingDirectorySeparator(path)) { - return path.substr(0, path.length - 1); - } - - return path; - } - - /** - * Adds a trailing directory separator to a path, if it does not already have one. - * @param path The path. - */ - export function ensureTrailingDirectorySeparator(path: Path): Path; - export function ensureTrailingDirectorySeparator(path: string): string; - export function ensureTrailingDirectorySeparator(path: string) { - if (!hasTrailingDirectorySeparator(path)) { - return path + directorySeparator; - } - - return path; - } - - // check path for these segments: '', '.'. '..' - const relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/; - - function comparePathsWorker(a: string, b: string, componentComparer: (a: string, b: string) => Comparison) { - if (a === b) return Comparison.EqualTo; - if (a === undefined) return Comparison.LessThan; - if (b === undefined) return Comparison.GreaterThan; - - // NOTE: Performance optimization - shortcut if the root segments differ as there would be no - // need to perform path reduction. - const aRoot = a.substring(0, getRootLength(a)); - const bRoot = b.substring(0, getRootLength(b)); - const result = compareStringsCaseInsensitive(aRoot, bRoot); - if (result !== Comparison.EqualTo) { - return result; - } - - // NOTE: Performance optimization - shortcut if there are no relative path segments in - // the non-root portion of the path - const aRest = a.substring(aRoot.length); - const bRest = b.substring(bRoot.length); - if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) { - return componentComparer(aRest, bRest); - } - - // The path contains a relative path segment. Normalize the paths and perform a slower component - // by component comparison. - const aComponents = reducePathComponents(getPathComponents(a)); - const bComponents = reducePathComponents(getPathComponents(b)); - const sharedLength = Math.min(aComponents.length, bComponents.length); - for (let i = 1; i < sharedLength; i++) { - const result = componentComparer(aComponents[i], bComponents[i]); - if (result !== Comparison.EqualTo) { - return result; - } - } - return compareValues(aComponents.length, bComponents.length); - } - - /** - * Performs a case-sensitive comparison of two paths. - */ - export function comparePathsCaseSensitive(a: string, b: string) { - return comparePathsWorker(a, b, compareStringsCaseSensitive); - } - - /** - * Performs a case-insensitive comparison of two paths. - */ - export function comparePathsCaseInsensitive(a: string, b: string) { - return comparePathsWorker(a, b, compareStringsCaseInsensitive); - } - - export function comparePaths(a: string, b: string, ignoreCase?: boolean): Comparison; - export function comparePaths(a: string, b: string, currentDirectory: string, ignoreCase?: boolean): Comparison; - export function comparePaths(a: string, b: string, currentDirectory?: string | boolean, ignoreCase?: boolean) { - if (typeof currentDirectory === "string") { - a = combinePaths(currentDirectory, a); - b = combinePaths(currentDirectory, b); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - return comparePathsWorker(a, b, getStringComparer(ignoreCase)); - } - - export function containsPath(parent: string, child: string, ignoreCase?: boolean): boolean; - export function containsPath(parent: string, child: string, currentDirectory: string, ignoreCase?: boolean): boolean; - export function containsPath(parent: string, child: string, currentDirectory?: string | boolean, ignoreCase?: boolean) { - if (typeof currentDirectory === "string") { - parent = combinePaths(currentDirectory, parent); - child = combinePaths(currentDirectory, child); - } - else if (typeof currentDirectory === "boolean") { - ignoreCase = currentDirectory; - } - if (parent === undefined || child === undefined) return false; - if (parent === child) return true; - const parentComponents = reducePathComponents(getPathComponents(parent)); - const childComponents = reducePathComponents(getPathComponents(child)); - if (childComponents.length < parentComponents.length) { - return false; - } - - const componentEqualityComparer = ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive; - for (let i = 0; i < parentComponents.length; i++) { - const equalityComparer = i === 0 ? equateStringsCaseInsensitive : componentEqualityComparer; - if (!equalityComparer(parentComponents[i], childComponents[i])) { - return false; - } - } - - return true; - } - - function isDirectorySeparator(charCode: number): boolean { - return charCode === CharacterCodes.slash || charCode === CharacterCodes.backslash; - } - function stripLeadingDirectorySeparator(s: string): string | undefined { - return isDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; + return isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined; } export function tryRemoveDirectoryPrefix(path: string, dirPath: string, getCanonicalFileName: GetCanonicalFileName): string | undefined { @@ -8250,10 +7705,6 @@ namespace ts { const wildcardCharCodes = [CharacterCodes.asterisk, CharacterCodes.question]; - export function hasExtension(fileName: string): boolean { - return stringContains(getBaseFileName(fileName), "."); - } - export const commonPackageFolders: readonly string[] = ["node_modules", "bower_components", "jspm_packages"]; const implicitExcludePathRegexPattern = `(?!(${commonPackageFolders.join("|")})(/|$))`; @@ -8718,13 +8169,6 @@ namespace ts { return changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false); } - export function changeAnyExtension(path: string, ext: string): string; - export function changeAnyExtension(path: string, ext: string, extensions: string | readonly string[], ignoreCase: boolean): string; - export function changeAnyExtension(path: string, ext: string, extensions?: string | readonly string[], ignoreCase?: boolean) { - const pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path); - return pathext ? path.slice(0, path.length - pathext.length) + (startsWith(ext, ".") ? ext : "." + ext) : path; - } - export function tryParsePattern(pattern: string): Pattern | undefined { // This should be verified outside of here and a proper error thrown. Debug.assert(hasZeroOrOneAsteriskCharacter(pattern)); @@ -8767,42 +8211,6 @@ namespace ts { return find(extensionsToRemove, e => fileExtensionIs(path, e)); } - function getAnyExtensionFromPathWorker(path: string, extensions: string | readonly string[], stringEqualityComparer: (a: string, b: string) => boolean) { - if (typeof extensions === "string") extensions = [extensions]; - for (let extension of extensions) { - if (!startsWith(extension, ".")) extension = "." + extension; - if (path.length >= extension.length && path.charAt(path.length - extension.length) === ".") { - const pathExtension = path.slice(path.length - extension.length); - if (stringEqualityComparer(pathExtension, extension)) { - return pathExtension; - } - } - } - return ""; - } - - /** - * Gets the file extension for a path. - */ - export function getAnyExtensionFromPath(path: string): string; - /** - * Gets the file extension for a path, provided it is one of the provided extensions. - */ - export function getAnyExtensionFromPath(path: string, extensions: string | readonly string[], ignoreCase: boolean): string; - export function getAnyExtensionFromPath(path: string, extensions?: string | readonly string[], ignoreCase?: boolean): string { - // Retrieves any string from the final "." onwards from a base file name. - // Unlike extensionFromPath, which throws an exception on unrecognized extensions. - if (extensions) { - return getAnyExtensionFromPathWorker(path, extensions, ignoreCase ? equateStringsCaseInsensitive : equateStringsCaseSensitive); - } - const baseFileName = getBaseFileName(path); - const extensionIndex = baseFileName.lastIndexOf("."); - if (extensionIndex >= 0) { - return baseFileName.substring(extensionIndex); - } - return ""; - } - export function isCheckJsEnabledForFile(sourceFile: SourceFile, compilerOptions: CompilerOptions) { return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs; } diff --git a/src/compiler/watch.ts b/src/compiler/watch.ts index 06871fc9cac..63b194c2077 100644 --- a/src/compiler/watch.ts +++ b/src/compiler/watch.ts @@ -91,7 +91,7 @@ namespace ts { /** Parses config file using System interface */ export function parseConfigFileWithSystem(configFileName: string, optionsToExtend: CompilerOptions, system: System, reportDiagnostic: DiagnosticReporter) { const host: ParseConfigFileHost = system; - host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(sys, reportDiagnostic, diagnostic); + host.onUnRecoverableConfigFileDiagnostic = diagnostic => reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); const result = getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host); host.onUnRecoverableConfigFileDiagnostic = undefined!; // TODO: GH#18217 return result; @@ -129,7 +129,7 @@ namespace ts { } export function listFiles(program: ProgramToEmitFilesAndReportErrors, writeFileName: (s: string) => void) { - if (program.getCompilerOptions().listFiles) { + if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) { forEach(program.getSourceFiles(), file => { writeFileName(file.fileName); }); @@ -149,6 +149,8 @@ namespace ts { emitOnlyDtsFiles?: boolean, customTransformers?: CustomTransformers ) { + const isListFilesOnly = !!program.getCompilerOptions().listFilesOnly; + // First get and report any syntactic errors. const diagnostics = program.getConfigFileParsingDiagnostics().slice(); const configFileParsingDiagnosticsLength = diagnostics.length; @@ -158,15 +160,20 @@ namespace ts { // semantic errors. if (diagnostics.length === configFileParsingDiagnosticsLength) { addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken)); - addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); - if (diagnostics.length === configFileParsingDiagnosticsLength) { - addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + if (!isListFilesOnly) { + addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken)); + + if (diagnostics.length === configFileParsingDiagnosticsLength) { + addRange(diagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken)); + } } } // Emit and report any errors we ran into. - const emitResult = program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); + const emitResult = isListFilesOnly + ? { emitSkipped: true, diagnostics: emptyArray } + : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); const { emittedFiles, diagnostics: emitDiagnostics } = emitResult; addRange(diagnostics, emitDiagnostics); diff --git a/src/debug/debug.ts b/src/debug/debug.ts new file mode 100644 index 00000000000..4314be10a49 --- /dev/null +++ b/src/debug/debug.ts @@ -0,0 +1,499 @@ +/// + +/* @internal */ +namespace Debug { + interface Node { + kind: number; + } + + type FunctionExpression = Node; + type ArrowFunction = Node; + type MethodDeclaration = Node; + type Expression = Node; + type SourceFile = Node; + + interface SwitchStatement extends Node { + caseBlock: CaseBlock; + } + + interface CaseBlock extends Node { + clauses: (CaseClause | DefaultClause)[]; + } + + interface CaseClause extends Node { + _caseclauseBrand: any; + expression: Expression; + } + + interface DefaultClause extends Node { + _defaultClauseBrand: any; + } + + interface TypeScriptModule { + readonly SyntaxKind: { + readonly CaseClause: number; + readonly DefaultClause: number; + }; + + readonly FlowFlags: { + readonly Unreachable: number, + readonly Start: number, + readonly BranchLabel: number, + readonly LoopLabel: number, + readonly Assignment: number, + readonly TrueCondition: number, + readonly FalseCondition: number, + readonly SwitchClause: number, + readonly ArrayMutation: number, + readonly Call: number, + readonly Referenced: number, + readonly Shared: number, + readonly PreFinally: number, + readonly AfterFinally: number, + readonly Label: number, + readonly Condition: number, + }; + + getSourceFileOfNode(node: Node): SourceFile; + getSourceTextOfNodeFromSourceFile(sourceFile: SourceFile, node: Node, includeTrivia?: boolean): string; + isDefaultClause(node: Node): node is DefaultClause; + } + + type FlowNode = + | AfterFinallyFlow + | PreFinallyFlow + | FlowStart + | FlowLabel + | FlowAssignment + | FlowCall + | FlowCondition + | FlowSwitchClause + | FlowArrayMutation + ; + + interface FlowNodeBase { + flags: FlowFlags; + id?: number; + } + + interface AfterFinallyFlow extends FlowNodeBase { + antecedent: FlowNode; + } + + interface PreFinallyFlow extends FlowNodeBase { + antecedent: FlowNode; + } + + interface FlowStart extends FlowNodeBase { + node?: FunctionExpression | ArrowFunction | MethodDeclaration; + } + + interface FlowLabel extends FlowNodeBase { + antecedents: FlowNode[] | undefined; + } + + interface FlowAssignment extends FlowNodeBase { + node: Expression; + antecedent: FlowNode; + } + + interface FlowCall extends FlowNodeBase { + node: Expression; + antecedent: FlowNode; + } + + interface FlowCondition extends FlowNodeBase { + node: Expression; + antecedent: FlowNode; + } + + interface FlowSwitchClause extends FlowNodeBase { + switchStatement: SwitchStatement; + clauseStart: number; + clauseEnd: number; + antecedent: FlowNode; + } + + interface FlowArrayMutation extends FlowNodeBase { + node: Expression; + antecedent: FlowNode; + } + + type FlowFlags = number; + let FlowFlags: TypeScriptModule["FlowFlags"]; + let getSourceFileOfNode: TypeScriptModule["getSourceFileOfNode"]; + let getSourceTextOfNodeFromSourceFile: TypeScriptModule["getSourceTextOfNodeFromSourceFile"]; + let isDefaultClause: TypeScriptModule["isDefaultClause"]; + + export function init(ts: TypeScriptModule) { + FlowFlags = ts.FlowFlags; + getSourceFileOfNode = ts.getSourceFileOfNode; + getSourceTextOfNodeFromSourceFile = ts.getSourceTextOfNodeFromSourceFile; + isDefaultClause = ts.isDefaultClause; + } + + let nextDebugFlowId = -1; + + function getDebugFlowNodeId(f: FlowNode) { + if (!f.id) { + f.id = nextDebugFlowId; + nextDebugFlowId--; + } + return f.id; + } + + export function formatControlFlowGraph(flowNode: FlowNode) { + const enum BoxCharacter { + lr = "─", + ud = "│", + dr = "╭", + dl = "╮", + ul = "╯", + ur = "╰", + udr = "├", + udl = "┤", + dlr = "┬", + ulr = "┴", + udlr = "╫", + } + + const enum Connection { + Up = 1 << 0, + Down = 1 << 1, + Left = 1 << 2, + Right = 1 << 3, + + UpDown = Up | Down, + LeftRight = Left | Right, + UpLeft = Up | Left, + UpRight = Up | Right, + DownLeft = Down | Left, + DownRight = Down | Right, + UpDownLeft = UpDown | Left, + UpDownRight = UpDown | Right, + UpLeftRight = Up | LeftRight, + DownLeftRight = Down | LeftRight, + UpDownLeftRight = UpDown | LeftRight, + + NoChildren = 1 << 4, + } + + interface FlowGraphNode { + id: number; + flowNode: FlowNode; + edges: FlowGraphEdge[]; + text: string; + lane: number; + endLane: number; + level: number; + } + + interface FlowGraphEdge { + source: FlowGraphNode; + target: FlowGraphNode; + } + + const hasAntecedentFlags = + FlowFlags.Assignment | + FlowFlags.Condition | + FlowFlags.SwitchClause | + FlowFlags.ArrayMutation | + FlowFlags.Call | + FlowFlags.PreFinally | + FlowFlags.AfterFinally; + + const hasNodeFlags = + FlowFlags.Start | + FlowFlags.Assignment | + FlowFlags.Call | + FlowFlags.Condition | + FlowFlags.ArrayMutation; + + const links: Record = Object.create(/*o*/ null); // eslint-disable-line no-null/no-null + const nodes: FlowGraphNode[] = []; + const edges: FlowGraphEdge[] = []; + const root = buildGraphNode(flowNode); + for (const node of nodes) { + computeLevel(node); + } + + const height = computeHeight(root); + const columnWidths = computeColumnWidths(height); + computeLanes(root, 0); + return renderGraph(); + + function isFlowSwitchClause(f: FlowNode): f is FlowSwitchClause { + return !!(f.flags & FlowFlags.SwitchClause); + } + + function hasAntecedents(f: FlowNode): f is FlowLabel & { antecedents: FlowNode[] } { + return !!(f.flags & FlowFlags.Label) && !!(f as FlowLabel).antecedents; + } + + function hasAntecedent(f: FlowNode): f is Extract { + return !!(f.flags & hasAntecedentFlags); + } + + function hasNode(f: FlowNode): f is Extract { + return !!(f.flags & hasNodeFlags); + } + + function getChildren(node: FlowGraphNode) { + const children: FlowGraphNode[] = []; + for (const edge of node.edges) { + if (edge.source === node) { + children.push(edge.target); + } + } + return children; + } + + function getParents(node: FlowGraphNode) { + const parents: FlowGraphNode[] = []; + for (const edge of node.edges) { + if (edge.target === node) { + parents.push(edge.source); + } + } + return parents; + } + + function buildGraphNode(flowNode: FlowNode) { + const id = getDebugFlowNodeId(flowNode); + let graphNode = links[id]; + if (!graphNode) { + links[id] = graphNode = { id, flowNode, edges: [], text: renderFlowNode(flowNode), lane: -1, endLane: -1, level: -1 }; + nodes.push(graphNode); + if (!(flowNode.flags & FlowFlags.PreFinally)) { + if (hasAntecedents(flowNode)) { + + for (const antecedent of flowNode.antecedents) { + buildGraphEdge(graphNode, antecedent); + } + } + else if (hasAntecedent(flowNode)) { + buildGraphEdge(graphNode, flowNode.antecedent); + } + } + } + return graphNode; + } + + function buildGraphEdge(source: FlowGraphNode, antecedent: FlowNode) { + const target = buildGraphNode(antecedent); + const edge: FlowGraphEdge = { source, target }; + edges.push(edge); + source.edges.push(edge); + target.edges.push(edge); + } + + function computeLevel(node: FlowGraphNode): number { + if (node.level !== -1) { + return node.level; + } + let level = 0; + for (const parent of getParents(node)) { + level = Math.max(level, computeLevel(parent) + 1); + } + return node.level = level; + } + + function computeHeight(node: FlowGraphNode): number { + let height = 0; + for (const child of getChildren(node)) { + height = Math.max(height, computeHeight(child)); + } + return height + 1; + } + + function computeColumnWidths(height: number) { + const columns: number[] = fill(Array(height), 0); + for (const node of nodes) { + columns[node.level] = Math.max(columns[node.level], node.text.length); + } + return columns; + } + + function computeLanes(node: FlowGraphNode, lane: number) { + if (node.lane === -1) { + node.lane = lane; + node.endLane = lane; + const children = getChildren(node); + for (let i = 0; i < children.length; i++) { + if (i > 0) lane++; + const child = children[i]; + computeLanes(child, lane); + if (child.endLane > node.endLane) { + lane = child.endLane; + } + } + node.endLane = lane; + } + } + + function getHeader(flags: FlowFlags) { + if (flags & FlowFlags.Start) return "Start"; + if (flags & FlowFlags.BranchLabel) return "Branch"; + if (flags & FlowFlags.LoopLabel) return "Loop"; + if (flags & FlowFlags.Assignment) return "Assignment"; + if (flags & FlowFlags.TrueCondition) return "True"; + if (flags & FlowFlags.FalseCondition) return "False"; + if (flags & FlowFlags.SwitchClause) return "SwitchClause"; + if (flags & FlowFlags.ArrayMutation) return "ArrayMutation"; + if (flags & FlowFlags.Call) return "Call"; + if (flags & FlowFlags.PreFinally) return "PreFinally"; + if (flags & FlowFlags.AfterFinally) return "AfterFinally"; + if (flags & FlowFlags.Unreachable) return "Unreachable"; + throw new Error(); + } + + function getNodeText(node: Node) { + const sourceFile = getSourceFileOfNode(node); + return getSourceTextOfNodeFromSourceFile(sourceFile, node, /*includeTrivia*/ false); + } + + function renderFlowNode(flowNode: FlowNode) { + let text = getHeader(flowNode.flags); + if (hasNode(flowNode)) { + if (flowNode.node) { + text += ` (${getNodeText(flowNode.node)})`; + } + } + else if (isFlowSwitchClause(flowNode)) { + const clauses: string[] = []; + for (let i = flowNode.clauseStart; i < flowNode.clauseEnd; i++) { + const clause = flowNode.switchStatement.caseBlock.clauses[i]; + if (isDefaultClause(clause)) { + clauses.push("default"); + } + else { + clauses.push(getNodeText(clause.expression)); + } + } + text += ` (${clauses.join(", ")})`; + } + return text; + } + + function renderGraph() { + const columnCount = columnWidths.length; + const laneCount = nodes.reduce((x, n) => Math.max(x, n.lane), 0) + 1; + const lanes: string[] = fill(Array(laneCount), ""); + const grid: (FlowGraphNode | undefined)[][] = columnWidths.map(() => Array(laneCount)); + const connectors: Connection[][] = columnWidths.map(() => fill(Array(laneCount), 0)); + + // build connectors + for (const node of nodes) { + grid[node.level][node.lane] = node; + const children = getChildren(node); + for (let i = 0; i < children.length; i++) { + const child = children[i]; + let connector: Connection = Connection.Right; + if (child.lane === node.lane) connector |= Connection.Left; + if (i > 0) connector |= Connection.Up; + if (i < children.length - 1) connector |= Connection.Down; + connectors[node.level][child.lane] |= connector; + } + if (children.length === 0) { + connectors[node.level][node.lane] |= Connection.NoChildren; + } + const parents = getParents(node); + for (let i = 0; i < parents.length; i++) { + const parent = parents[i]; + let connector: Connection = Connection.Left; + if (i > 0) connector |= Connection.Up; + if (i < parents.length - 1) connector |= Connection.Down; + connectors[node.level - 1][parent.lane] |= connector; + } + } + + // fill in missing connectors + for (let column = 0; column < columnCount; column++) { + for (let lane = 0; lane < laneCount; lane++) { + const left = column > 0 ? connectors[column - 1][lane] : 0; + const above = lane > 0 ? connectors[column][lane - 1] : 0; + let connector = connectors[column][lane]; + if (!connector) { + if (left & Connection.Right) connector |= Connection.LeftRight; + if (above & Connection.Down) connector |= Connection.UpDown; + connectors[column][lane] = connector; + } + } + } + + for (let column = 0; column < columnCount; column++) { + for (let lane = 0; lane < lanes.length; lane++) { + const connector = connectors[column][lane]; + const fill = connector & Connection.Left ? BoxCharacter.lr : " "; + const node = grid[column][lane]; + if (!node) { + if (column < columnCount - 1) { + writeLane(lane, repeat(fill, columnWidths[column] + 1)); + } + } + else { + writeLane(lane, node.text); + if (column < columnCount - 1) { + writeLane(lane, " "); + writeLane(lane, repeat(fill, columnWidths[column] - node.text.length)); + } + } + writeLane(lane, getBoxCharacter(connector)); + writeLane(lane, connector & Connection.Right && column < columnCount - 1 && !grid[column + 1][lane] ? BoxCharacter.lr : " "); + } + } + + return `\n${lanes.join("\n")}\n`; + + function writeLane(lane: number, text: string) { + lanes[lane] += text; + } + } + + function getBoxCharacter(connector: Connection) { + switch (connector) { + case Connection.UpDown: return BoxCharacter.ud; + case Connection.LeftRight: return BoxCharacter.lr; + case Connection.UpLeft: return BoxCharacter.ul; + case Connection.UpRight: return BoxCharacter.ur; + case Connection.DownLeft: return BoxCharacter.dl; + case Connection.DownRight: return BoxCharacter.dr; + case Connection.UpDownLeft: return BoxCharacter.udl; + case Connection.UpDownRight: return BoxCharacter.udr; + case Connection.UpLeftRight: return BoxCharacter.ulr; + case Connection.DownLeftRight: return BoxCharacter.dlr; + case Connection.UpDownLeftRight: return BoxCharacter.udlr; + } + return " "; + } + + function fill(array: T[], value: T) { + if (array.fill) { + array.fill(value); + } + else { + for (let i = 0; i < array.length; i++) { + array[i] = value; + } + } + return array; + } + + function repeat(ch: string, length: number) { + if (ch.repeat) { + return length > 0 ? ch.repeat(length) : ""; + } + let s = ""; + while (s.length < length) { + s += ch; + } + return s; + } + } + + // Export as a module. NOTE: Can't use module exports as this is built using --outFile + declare const module: { exports: {} }; + if (typeof module !== "undefined" && module.exports) { + module.exports = Debug; + } +} \ No newline at end of file diff --git a/src/debug/tsconfig.json b/src/debug/tsconfig.json new file mode 100644 index 00000000000..471ae4ad34a --- /dev/null +++ b/src/debug/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "../tsconfig-library-base", + "compilerOptions": { + "target": "es2019", + "lib": ["es2019"], + "outFile": "../../built/local/compiler-debug.js", + "declaration": false, + "sourceMap": true + }, + "files": [ + "debug.ts" + ] +} diff --git a/src/harness/client.ts b/src/harness/client.ts index 352db2fe2b3..046a5303040 100644 --- a/src/harness/client.ts +++ b/src/harness/client.ts @@ -290,7 +290,7 @@ namespace ts.server { const args: protocol.FileLocationRequestArgs = this.createFileLocationRequestArgs(fileName, position); const request = this.processRequest(CommandNames.DefinitionAndBoundSpan, args); - const response = this.processResponse(request); + const response = this.processResponse(request); const body = Debug.assertDefined(response.body); // TODO: GH#18217 return { diff --git a/src/harness/fakes.ts b/src/harness/fakes.ts index adcaef55471..d14d8dd2a71 100644 --- a/src/harness/fakes.ts +++ b/src/harness/fakes.ts @@ -524,7 +524,7 @@ ${indentText}${text}`; export const version = "FakeTSVersion"; - export function patchSolutionBuilderHost(host: ts.SolutionBuilderHost, sys: System) { + export function patchHostForBuildInfoReadWrite(host: ts.CompilerHost | ts.SolutionBuilderHost) { const originalReadFile = host.readFile; host.readFile = (path, encoding) => { const value = originalReadFile.call(host, path, encoding); @@ -537,7 +537,7 @@ ${indentText}${text}`; if (host.writeFile) { const originalWriteFile = host.writeFile; - host.writeFile = (fileName, content, writeByteOrderMark) => { + host.writeFile = (fileName: string, content: string, writeByteOrderMark: boolean) => { if (!ts.isBuildInfoFile(fileName)) return originalWriteFile.call(host, fileName, content, writeByteOrderMark); const buildInfo = ts.getBuildInfo(content); sanitizeBuildInfoProgram(buildInfo); @@ -545,6 +545,10 @@ ${indentText}${text}`; originalWriteFile.call(host, fileName, ts.getBuildInfoText(buildInfo), writeByteOrderMark); }; } + } + + export function patchSolutionBuilderHost(host: ts.SolutionBuilderHost, sys: System) { + patchHostForBuildInfoReadWrite(host); ts.Debug.assert(host.now === undefined); host.now = () => new Date(sys.vfs.time()); diff --git a/src/harness/fourslash.ts b/src/harness/fourslash.ts index b6a1cf72f3c..f6680378617 100644 --- a/src/harness/fourslash.ts +++ b/src/harness/fourslash.ts @@ -775,7 +775,9 @@ namespace FourSlash { private verifyCompletionsWorker(options: FourSlashInterface.VerifyCompletionsOptions): void { const actualCompletions = this.getCompletionListAtCaret({ ...options.preferences, triggerCharacter: options.triggerCharacter })!; if (!actualCompletions) { - if (ts.hasProperty(options, "exact") && options.exact === undefined) return; + if (ts.hasProperty(options, "exact") && (options.exact === undefined || ts.isArray(options.exact) && !options.exact.length)) { + return; + } this.raiseError(`No completions at position '${this.currentCaretPosition}'.`); } @@ -4894,12 +4896,14 @@ namespace FourSlashInterface { "declare", "keyof", "module", + "namespace", "never", "readonly", "number", "object", "string", "symbol", + "type", "unique", "unknown", "bigint", @@ -5091,12 +5095,14 @@ namespace FourSlashInterface { "declare", "keyof", "module", + "namespace", "never", "readonly", "number", "object", "string", "symbol", + "type", "unique", "unknown", "bigint", diff --git a/src/harness/harnessLanguageService.ts b/src/harness/harnessLanguageService.ts index 67fc45c4807..e355a7c6647 100644 --- a/src/harness/harnessLanguageService.ts +++ b/src/harness/harnessLanguageService.ts @@ -220,6 +220,10 @@ namespace Harness.LanguageService { return !!this.typesRegistry && this.typesRegistry.has(name); } + getGlobalTypingsCacheLocation() { + return "/Library/Caches/typescript"; + } + installPackage = ts.notImplemented; getCompilationSettings() { return this.settings; } @@ -796,7 +800,7 @@ namespace Harness.LanguageService { return mockHash(s); } - require(_initialDir: string, _moduleName: string): ts.server.RequireResult { + require(_initialDir: string, _moduleName: string): ts.RequireResult { switch (_moduleName) { // Adds to the Quick Info a fixed string and a string from the config file // and replaces the first display part diff --git a/src/harness/virtualFileSystemWithWatch.ts b/src/harness/virtualFileSystemWithWatch.ts index 0417ad55c99..42834d46880 100644 --- a/src/harness/virtualFileSystemWithWatch.ts +++ b/src/harness/virtualFileSystemWithWatch.ts @@ -341,7 +341,7 @@ interface Array { length: number; [n: number]: T; }` private readonly currentDirectory: string; private readonly customWatchFile: HostWatchFile | undefined; private readonly customRecursiveWatchDirectory: HostWatchDirectory | undefined; - public require: ((initialPath: string, moduleName: string) => server.RequireResult) | undefined; + public require: ((initialPath: string, moduleName: string) => RequireResult) | undefined; constructor( public withSafeList: boolean, diff --git a/src/lib/dom.generated.d.ts b/src/lib/dom.generated.d.ts index 5f1d2415189..f9f75763a39 100644 --- a/src/lib/dom.generated.d.ts +++ b/src/lib/dom.generated.d.ts @@ -9762,7 +9762,7 @@ interface ImageData { declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height?: number): ImageData; }; interface InnerHTML { @@ -19083,7 +19083,7 @@ declare namespace WebAssembly { var Instance: { prototype: Instance; - new(module: Module, importObject?: any): Instance; + new(module: Module, importObject?: Imports): Instance; }; interface LinkError { diff --git a/src/lib/es5.d.ts b/src/lib/es5.d.ts index 99acdcf8b8e..8c11be587a1 100644 --- a/src/lib/es5.d.ts +++ b/src/lib/es5.d.ts @@ -682,8 +682,8 @@ interface Math { /** Returns a pseudorandom number between 0 and 1. */ random(): number; /** - * Returns a supplied numeric expression rounded to the nearest number. - * @param x The value to be rounded to the nearest number. + * Returns a supplied numeric expression rounded to the nearest integer. + * @param x The value to be rounded to the nearest integer. */ round(x: number): number; /** @@ -873,12 +873,12 @@ interface DateConstructor { /** * Returns the number of milliseconds between midnight, January 1, 1970 Universal Coordinated Time (UTC) (or GMT) and the specified date. * @param year The full year designation is required for cross-century date accuracy. If year is between 0 and 99 is used, then year is assumed to be 1900 + year. - * @param month The month as an number between 0 and 11 (January to December). - * @param date The date as an number between 1 and 31. - * @param hours Must be supplied if minutes is supplied. An number from 0 to 23 (midnight to 11pm) that specifies the hour. - * @param minutes Must be supplied if seconds is supplied. An number from 0 to 59 that specifies the minutes. - * @param seconds Must be supplied if milliseconds is supplied. An number from 0 to 59 that specifies the seconds. - * @param ms An number from 0 to 999 that specifies the milliseconds. + * @param month The month as a number between 0 and 11 (January to December). + * @param date The date as a number between 1 and 31. + * @param hours Must be supplied if minutes is supplied. A number from 0 to 23 (midnight to 11pm) that specifies the hour. + * @param minutes Must be supplied if seconds is supplied. A number from 0 to 59 that specifies the minutes. + * @param seconds Must be supplied if milliseconds is supplied. A number from 0 to 59 that specifies the seconds. + * @param ms A number from 0 to 999 that specifies the milliseconds. */ UTC(year: number, month: number, date?: number, hours?: number, minutes?: number, seconds?: number, ms?: number): number; now(): number; diff --git a/src/lib/webworker.generated.d.ts b/src/lib/webworker.generated.d.ts index 691c9d4820e..0199e62b9df 100644 --- a/src/lib/webworker.generated.d.ts +++ b/src/lib/webworker.generated.d.ts @@ -2202,7 +2202,7 @@ interface ImageData { declare var ImageData: { prototype: ImageData; new(width: number, height: number): ImageData; - new(array: Uint8ClampedArray, width: number, height: number): ImageData; + new(array: Uint8ClampedArray, width: number, height?: number): ImageData; }; /** This Channel Messaging API interface allows us to create a new message channel and send data through it via its two MessagePort properties. */ @@ -5609,7 +5609,7 @@ declare namespace WebAssembly { var Instance: { prototype: Instance; - new(module: Module, importObject?: any): Instance; + new(module: Module, importObject?: Imports): Instance; }; interface Memory { diff --git a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl index 56bd64e882e..0b518c5f625 100644 --- a/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/chs/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -4087,7 +4087,7 @@ - + @@ -4987,7 +4987,7 @@ - + diff --git a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl index 32430664b71..74c16b4fa96 100644 --- a/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/cht/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -25,7 +25,7 @@ - + @@ -34,7 +34,7 @@ - + @@ -88,7 +88,7 @@ - + @@ -265,7 +265,7 @@ - + @@ -274,7 +274,7 @@ - + @@ -886,7 +886,7 @@ - + @@ -934,7 +934,7 @@ - + @@ -961,7 +961,7 @@ - + @@ -1129,7 +1129,7 @@ - + @@ -1363,7 +1363,7 @@ - + @@ -1381,7 +1381,7 @@ - + @@ -1417,7 +1417,7 @@ - + @@ -1480,7 +1480,7 @@ - + @@ -1708,7 +1708,7 @@ - + @@ -4087,7 +4087,7 @@ - + @@ -5260,7 +5260,7 @@ - + @@ -9325,7 +9325,7 @@ - + @@ -9334,7 +9334,7 @@ - + @@ -9343,7 +9343,7 @@ - + @@ -9352,7 +9352,7 @@ - + @@ -9361,7 +9361,7 @@ - + @@ -9370,7 +9370,7 @@ - + @@ -9379,7 +9379,7 @@ - + @@ -9388,7 +9388,7 @@ - + @@ -9397,7 +9397,7 @@ - + @@ -9406,7 +9406,7 @@ - + @@ -9415,7 +9415,7 @@ - + @@ -9424,7 +9424,7 @@ - + @@ -9433,7 +9433,7 @@ - + @@ -9496,7 +9496,7 @@ - + @@ -9649,7 +9649,7 @@ - + @@ -9874,7 +9874,7 @@ - + diff --git a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl index 8eca13ad9cd..ce9c719d796 100644 --- a/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/csy/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,4 +1,4 @@ - + @@ -4096,7 +4096,7 @@ - + diff --git a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl index d2461ce0c42..62dc9fc878a 100644 --- a/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/deu/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,10133 +1,10133 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - or -. For example '{0}' or '{1}'.]]> - - oder - erforderlich, z. B. "{0}" oder "{1}".]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - type.]]> - - " sein.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ()' instead.]]> - - ()".]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + oder - erforderlich, z. B. "{0}" oder "{1}".]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + " sein.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + ()".]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl index 1760da2a463..1b1a735c1dc 100644 --- a/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/esn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,10151 +1,10151 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - or -. For example '{0}' or '{1}'.]]> - - o -. Por ejemplo, '{0}' o '{1}'.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - type.]]> - - global.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ()' instead.]]> - - ()" en su lugar.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + o -. Por ejemplo, '{0}' o '{1}'.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + global.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + ()" en su lugar.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl index b3fd8ed1b5d..6988db6bec2 100644 --- a/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/fra/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,4 +1,4 @@ - + @@ -1348,7 +1348,7 @@ - + @@ -5539,7 +5539,7 @@ - + @@ -6916,7 +6916,7 @@ - + diff --git a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl index 4a7941396b4..3103936fb50 100644 --- a/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/jpn/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1228,7 +1228,7 @@ - + @@ -1336,7 +1336,7 @@ - + @@ -1345,7 +1345,7 @@ - + @@ -1354,7 +1354,7 @@ - + @@ -1363,7 +1363,7 @@ - + @@ -3610,7 +3610,7 @@ - + @@ -3619,7 +3619,7 @@ - + @@ -3703,7 +3703,7 @@ - + @@ -4390,7 +4390,7 @@ - + @@ -4987,7 +4987,7 @@ - + @@ -6622,7 +6622,7 @@ - + @@ -7870,7 +7870,7 @@ - + @@ -8170,7 +8170,7 @@ - + @@ -9535,7 +9535,7 @@ - + @@ -9601,7 +9601,7 @@ - + diff --git a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl index c7210cd103b..a8cc5abc678 100644 --- a/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/kor/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -9856,7 +9856,7 @@ - + diff --git a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 79e9f73d205..5c051c2d201 100644 --- a/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/plk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -303,7 +303,7 @@ - + @@ -4077,7 +4077,7 @@ - + @@ -5517,7 +5517,7 @@ - + @@ -6891,7 +6891,7 @@ - + diff --git a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl index cf26e2044e7..313874dc994 100644 --- a/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/ptb/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -1,10129 +1,10129 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - or -. For example '{0}' or '{1}'.]]> - - ou -. Por exemplo '{0}' ou '{1}'.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - type.]]> - - Promessa global.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ()' instead.]]> - - ()' em vez disso.]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + or -. For example '{0}' or '{1}'.]]> + + ou -. Por exemplo '{0}' ou '{1}'.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + type.]]> + + Promessa global.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + ()' instead.]]> + + ()' em vez disso.]]> + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl index 5ba07d067e1..b16f07d9bc8 100644 --- a/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/rus/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -309,7 +309,7 @@ - + @@ -978,7 +978,7 @@ - + @@ -987,7 +987,7 @@ - + @@ -1227,7 +1227,7 @@ - + @@ -1335,7 +1335,7 @@ - + @@ -1344,7 +1344,7 @@ - + @@ -1353,7 +1353,7 @@ - + @@ -1362,7 +1362,7 @@ - + @@ -3618,7 +3618,7 @@ - + @@ -4086,7 +4086,7 @@ - + @@ -5526,7 +5526,7 @@ - + @@ -6621,7 +6621,7 @@ - + @@ -6903,7 +6903,7 @@ - + @@ -7869,7 +7869,7 @@ - + @@ -9600,7 +9600,7 @@ - + diff --git a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl index 0b60df175fe..37122673a1f 100644 --- a/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl +++ b/src/loc/lcl/trk/diagnosticMessages/diagnosticMessages.generated.json.lcl @@ -4188,7 +4188,7 @@ - + diff --git a/src/server/editorServices.ts b/src/server/editorServices.ts index 2ed4a903133..f7d220b7894 100644 --- a/src/server/editorServices.ts +++ b/src/server/editorServices.ts @@ -1533,6 +1533,14 @@ namespace ts.server { return undefined; } + /*@internal*/ + findDefaultConfiguredProject(info: ScriptInfo) { + if (!info.isScriptOpen()) return undefined; + const configFileName = this.getConfigFileNameForFile(info); + return configFileName && + this.findConfiguredProjectByProjectName(configFileName); + } + /** * This function tries to search for a tsconfig.json for the given file. * This is different from the method the compiler uses because diff --git a/src/server/project.ts b/src/server/project.ts index 3f8dfa07c98..c98e7660b38 100644 --- a/src/server/project.ts +++ b/src/server/project.ts @@ -307,6 +307,11 @@ namespace ts.server { return this.typingsCache.installPackage({ ...options, projectName: this.projectName, projectRootPath: this.toPath(this.currentDirectory) }); } + /*@internal*/ + getGlobalTypingsCacheLocation() { + return this.getGlobalCache(); + } + private get typingsCache(): TypingsCache { return this.projectService.typingsCache; } diff --git a/src/server/protocol.ts b/src/server/protocol.ts index 01c8434228f..925e7638f9d 100644 --- a/src/server/protocol.ts +++ b/src/server/protocol.ts @@ -918,10 +918,13 @@ namespace ts.server.protocol { body?: FileSpanWithContext[]; } - export interface DefinitionInfoAndBoundSpanReponse extends Response { + export interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; } + /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ + export type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; + /** * Definition response message. Gives text range for definition. */ @@ -3004,6 +3007,12 @@ namespace ts.server.protocol { * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. */ readonly includeCompletionsWithInsertText?: boolean; + /** + * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled, + * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined + * values, with insertion text to replace preceding `.` tokens with `?.`. + */ + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; readonly lazyConfiguredProjectsFromExternalProject?: boolean; diff --git a/src/server/scriptInfo.ts b/src/server/scriptInfo.ts index f602d18ae70..86d76711d4a 100644 --- a/src/server/scriptInfo.ts +++ b/src/server/scriptInfo.ts @@ -491,21 +491,40 @@ namespace ts.server { case 1: return this.containingProjects[0]; default: - // if this file belongs to multiple projects, the first configured project should be - // the default project; if no configured projects, the first external project should - // be the default project; otherwise the first inferred project should be the default. + // If this file belongs to multiple projects, below is the order in which default project is used + // - for open script info, its default configured project during opening is default if info is part of it + // - first configured project of which script info is not a source of project reference redirect + // - first configured project + // - first external project + // - first inferred project let firstExternalProject; let firstConfiguredProject; - for (const project of this.containingProjects) { + let firstNonSourceOfProjectReferenceRedirect; + let defaultConfiguredProject: ConfiguredProject | false | undefined; + for (let index = 0; index < this.containingProjects.length; index++) { + const project = this.containingProjects[index]; if (project.projectKind === ProjectKind.Configured) { - if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) return project; + if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) { + // If we havent found default configuredProject and + // its not the last one, find it and use that one if there + if (defaultConfiguredProject === undefined && + index !== this.containingProjects.length - 1) { + defaultConfiguredProject = project.projectService.findDefaultConfiguredProject(this) || false; + } + if (defaultConfiguredProject === project) return project; + if (!firstNonSourceOfProjectReferenceRedirect) firstNonSourceOfProjectReferenceRedirect = project; + } if (!firstConfiguredProject) firstConfiguredProject = project; } else if (project.projectKind === ProjectKind.External && !firstExternalProject) { firstExternalProject = project; } } - return firstConfiguredProject || firstExternalProject || this.containingProjects[0]; + return defaultConfiguredProject || + firstNonSourceOfProjectReferenceRedirect || + firstConfiguredProject || + firstExternalProject || + this.containingProjects[0]; } } diff --git a/src/services/classifier.ts b/src/services/classifier.ts index a18f861db2d..69d1dcdf8e6 100644 --- a/src/services/classifier.ts +++ b/src/services/classifier.ts @@ -499,8 +499,10 @@ namespace ts { return { spans, endOfLineState: EndOfLineState.None }; function pushClassification(start: number, end: number, type: ClassificationType): void { + const length = end - start; + Debug.assert(length > 0, `Classification had non-positive length of ${length}`); spans.push(start); - spans.push(end - start); + spans.push(length); spans.push(type); } } @@ -985,8 +987,7 @@ namespace ts { return ClassificationType.bigintLiteral; } else if (tokenKind === SyntaxKind.StringLiteral) { - // TODO: GH#18217 - return token!.parent.kind === SyntaxKind.JsxAttribute ? ClassificationType.jsxAttributeStringLiteralValue : ClassificationType.stringLiteral; + return token && token.parent.kind === SyntaxKind.JsxAttribute ? ClassificationType.jsxAttributeStringLiteralValue : ClassificationType.stringLiteral; } else if (tokenKind === SyntaxKind.RegularExpressionLiteral) { // TODO: we should get another classification type for these literals. diff --git a/src/services/codefixes/helpers.ts b/src/services/codefixes/helpers.ts index 307e49c0c44..b127fa24048 100644 --- a/src/services/codefixes/helpers.ts +++ b/src/services/codefixes/helpers.ts @@ -233,14 +233,14 @@ namespace ts.codefix { let someSigHasRestParameter = false; for (const sig of signatures) { minArgumentCount = Math.min(sig.minArgumentCount, minArgumentCount); - if (sig.hasRestParameter) { + if (signatureHasRestParameter(sig)) { someSigHasRestParameter = true; } - if (sig.parameters.length >= maxArgsSignature.parameters.length && (!sig.hasRestParameter || maxArgsSignature.hasRestParameter)) { + if (sig.parameters.length >= maxArgsSignature.parameters.length && (!signatureHasRestParameter(sig) || signatureHasRestParameter(maxArgsSignature))) { maxArgsSignature = sig; } } - const maxNonRestArgs = maxArgsSignature.parameters.length - (maxArgsSignature.hasRestParameter ? 1 : 0); + const maxNonRestArgs = maxArgsSignature.parameters.length - (signatureHasRestParameter(maxArgsSignature) ? 1 : 0); const maxArgsParameterSymbolNames = maxArgsSignature.parameters.map(symbol => symbol.name); const parameters = createDummyParameters(maxNonRestArgs, maxArgsParameterSymbolNames, /* types */ undefined, minArgumentCount, /*inJs*/ false); diff --git a/src/services/codefixes/importFixes.ts b/src/services/codefixes/importFixes.ts index 44adb40c554..a43aa7f6f9d 100644 --- a/src/services/codefixes/importFixes.ts +++ b/src/services/codefixes/importFixes.ts @@ -631,6 +631,7 @@ namespace ts.codefix { let filteredCount = 0; const packageJson = filterByPackageJson && createAutoImportFilter(from, program, host); const allSourceFiles = program.getSourceFiles(); + const globalTypingsCache = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation(); forEachExternalModule(program.getTypeChecker(), allSourceFiles, (module, sourceFile) => { if (sourceFile === undefined) { if (!packageJson || packageJson.allowsImportingAmbientModule(module, allSourceFiles)) { @@ -640,7 +641,10 @@ namespace ts.codefix { filteredCount++; } } - else if (sourceFile && sourceFile !== from && isImportablePath(from.fileName, sourceFile.fileName)) { + else if (sourceFile && + sourceFile !== from && + isImportablePath(from.fileName, sourceFile.fileName, hostGetCanonicalFileName(host), globalTypingsCache) + ) { if (!packageJson || packageJson.allowsImportingSourceFile(sourceFile, allSourceFiles)) { cb(module); } @@ -669,10 +673,13 @@ namespace ts.codefix { * Don't include something from a `node_modules` that isn't actually reachable by a global import. * A relative import to node_modules is usually a bad idea. */ - function isImportablePath(fromPath: string, toPath: string): boolean { + function isImportablePath(fromPath: string, toPath: string, getCanonicalFileName: GetCanonicalFileName, globalCachePath?: string): boolean { // If it's in a `node_modules` but is not reachable from here via a global import, don't bother. const toNodeModules = forEachAncestorDirectory(toPath, ancestor => getBaseFileName(ancestor) === "node_modules" ? ancestor : undefined); - return toNodeModules === undefined || startsWith(fromPath, getDirectoryPath(toNodeModules)); + const toNodeModulesParent = toNodeModules && getDirectoryPath(getCanonicalFileName(toNodeModules)); + return toNodeModulesParent === undefined + || startsWith(getCanonicalFileName(fromPath), toNodeModulesParent) + || (!!globalCachePath && startsWith(getCanonicalFileName(globalCachePath), toNodeModulesParent)); } export function moduleSymbolToValidIdentifier(moduleSymbol: Symbol, target: ScriptTarget): string { @@ -718,6 +725,7 @@ namespace ts.codefix { readFile: maybeBind(host, host.readFile), useCaseSensitiveFileNames: maybeBind(host, host.useCaseSensitiveFileNames), getProbableSymlinks: maybeBind(host, host.getProbableSymlinks) || program.getProbableSymlinks, + getGlobalTypingsCacheLocation: maybeBind(host, host.getGlobalTypingsCacheLocation), }; let usesNodeCoreModules: boolean | undefined; diff --git a/src/services/codefixes/inferFromUsage.ts b/src/services/codefixes/inferFromUsage.ts index 11c3fbace61..acd2a295d58 100644 --- a/src/services/codefixes/inferFromUsage.ts +++ b/src/services/codefixes/inferFromUsage.ts @@ -49,21 +49,21 @@ namespace ts.codefix { registerCodeFix({ errorCodes, getCodeActions(context) { - const { sourceFile, program, span: { start }, errorCode, cancellationToken, host } = context; + const { sourceFile, program, span: { start }, errorCode, cancellationToken, host, formatContext, preferences } = context; const token = getTokenAtPosition(sourceFile, start); let declaration!: Declaration | undefined; - const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host); }); + const changes = textChanges.ChangeTracker.with(context, changes => { declaration = doChange(changes, sourceFile, token, errorCode, program, cancellationToken, /*markSeen*/ returnTrue, host, formatContext, preferences); }); const name = declaration && getNameOfDeclaration(declaration); return !name || changes.length === 0 ? undefined : [createCodeFixAction(fixId, changes, [getDiagnostic(errorCode, token), name.getText(sourceFile)], fixId, Diagnostics.Infer_all_types_from_usage)]; }, fixIds: [fixId], getAllCodeActions(context) { - const { sourceFile, program, cancellationToken, host } = context; + const { sourceFile, program, cancellationToken, host, formatContext, preferences } = context; const markSeen = nodeSeenTracker(); return codeFixAll(context, errorCodes, (changes, err) => { - doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host); + doChange(changes, sourceFile, getTokenAtPosition(err.file, err.start), err.code, program, cancellationToken, markSeen, host, formatContext, preferences); }); }, }); @@ -106,7 +106,7 @@ namespace ts.codefix { return errorCode; } - function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost): Declaration | undefined { + function doChange(changes: textChanges.ChangeTracker, sourceFile: SourceFile, token: Node, errorCode: number, program: Program, cancellationToken: CancellationToken, markSeen: NodeSeenTracker, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences): Declaration | undefined { if (!isParameterPropertyModifier(token.kind) && token.kind !== SyntaxKind.Identifier && token.kind !== SyntaxKind.DotDotDotToken && token.kind !== SyntaxKind.ThisKeyword) { return undefined; } @@ -118,7 +118,7 @@ namespace ts.codefix { case Diagnostics.Member_0_implicitly_has_an_1_type.code: case Diagnostics.Variable_0_implicitly_has_type_1_in_some_locations_where_its_type_cannot_be_determined.code: if ((isVariableDeclaration(parent) && markSeen(parent)) || isPropertyDeclaration(parent) || isPropertySignature(parent)) { // handle bad location - annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, parent, program, host, cancellationToken, formatContext, preferences); return parent; } if (isPropertyAccessExpression(parent)) { @@ -136,7 +136,7 @@ namespace ts.codefix { case Diagnostics.Variable_0_implicitly_has_an_1_type.code: { const symbol = program.getTypeChecker().getSymbolAtLocation(token); if (symbol && symbol.valueDeclaration && isVariableDeclaration(symbol.valueDeclaration) && markSeen(symbol.valueDeclaration)) { - annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken); + annotateVariableDeclaration(changes, sourceFile, symbol.valueDeclaration, program, host, cancellationToken, formatContext, preferences); return symbol.valueDeclaration; } return undefined; @@ -152,14 +152,14 @@ namespace ts.codefix { // Parameter declarations case Diagnostics.Parameter_0_implicitly_has_an_1_type.code: if (isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } // falls through case Diagnostics.Rest_parameter_0_implicitly_has_an_any_type.code: if (markSeen(containingFunction)) { const param = cast(parent, isParameter); - annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken); + annotateParameters(changes, sourceFile, param, containingFunction, program, host, cancellationToken, formatContext, preferences); return param; } return undefined; @@ -168,7 +168,7 @@ namespace ts.codefix { case Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation.code: case Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type.code: if (isGetAccessorDeclaration(containingFunction) && isIdentifier(containingFunction.name)) { - annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, containingFunction, inferTypeForVariableFromUsage(containingFunction.name, program, cancellationToken), program, host, formatContext, preferences); return containingFunction; } return undefined; @@ -176,7 +176,7 @@ namespace ts.codefix { // Set Accessor declarations case Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation.code: if (isSetAccessorDeclaration(containingFunction)) { - annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken); + annotateSetAccessor(changes, sourceFile, containingFunction, program, host, cancellationToken, formatContext, preferences); return containingFunction; } return undefined; @@ -194,13 +194,32 @@ namespace ts.codefix { } } - function annotateVariableDeclaration(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { + function annotateVariableDeclaration( + changes: textChanges.ChangeTracker, + sourceFile: SourceFile, + declaration: VariableDeclaration | PropertyDeclaration | PropertySignature, + program: Program, + host: LanguageServiceHost, + cancellationToken: CancellationToken, + formatContext: formatting.FormatContext, + preferences: UserPreferences, + ): void { if (isIdentifier(declaration.name)) { - annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host); + annotate(changes, sourceFile, declaration, inferTypeForVariableFromUsage(declaration.name, program, cancellationToken), program, host, formatContext, preferences); } } - function annotateParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterDeclaration: ParameterDeclaration, containingFunction: FunctionLike, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { + function annotateParameters( + changes: textChanges.ChangeTracker, + sourceFile: SourceFile, + parameterDeclaration: ParameterDeclaration, + containingFunction: FunctionLike, + program: Program, + host: LanguageServiceHost, + cancellationToken: CancellationToken, + formatContext: formatting.FormatContext, + preferences: UserPreferences, + ): void { if (!isIdentifier(parameterDeclaration.name)) { return; } @@ -216,7 +235,7 @@ namespace ts.codefix { if (needParens) changes.insertNodeBefore(sourceFile, first(containingFunction.parameters), createToken(SyntaxKind.OpenParenToken)); for (const { declaration, type } of parameterInferences) { if (declaration && !declaration.type && !declaration.initializer) { - annotate(changes, sourceFile, declaration, type, program, host); + annotate(changes, sourceFile, declaration, type, program, host, formatContext, preferences); } } if (needParens) changes.insertNodeAfter(sourceFile, last(containingFunction.parameters), createToken(SyntaxKind.CloseParenToken)); @@ -248,7 +267,16 @@ namespace ts.codefix { ]); } - function annotateSetAccessor(changes: textChanges.ChangeTracker, sourceFile: SourceFile, setAccessorDeclaration: SetAccessorDeclaration, program: Program, host: LanguageServiceHost, cancellationToken: CancellationToken): void { + function annotateSetAccessor( + changes: textChanges.ChangeTracker, + sourceFile: SourceFile, + setAccessorDeclaration: SetAccessorDeclaration, + program: Program, + host: LanguageServiceHost, + cancellationToken: CancellationToken, + formatContext: formatting.FormatContext, + preferences: UserPreferences, + ): void { const param = firstOrUndefined(setAccessorDeclaration.parameters); if (param && isIdentifier(setAccessorDeclaration.name) && isIdentifier(param.name)) { let type = inferTypeForVariableFromUsage(setAccessorDeclaration.name, program, cancellationToken); @@ -259,12 +287,12 @@ namespace ts.codefix { annotateJSDocParameters(changes, sourceFile, [{ declaration: param, type }], program, host); } else { - annotate(changes, sourceFile, param, type, program, host); + annotate(changes, sourceFile, param, type, program, host, formatContext, preferences); } } } - function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type, program: Program, host: LanguageServiceHost): void { + function annotate(changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type, program: Program, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences): void { const typeNode = getTypeNodeIfAccessible(type, declaration, program, host); if (typeNode) { if (isInJSFile(sourceFile) && declaration.kind !== SyntaxKind.PropertySignature) { @@ -276,12 +304,42 @@ namespace ts.codefix { const typeTag = isGetAccessorDeclaration(declaration) ? createJSDocReturnTag(typeExpression, "") : createJSDocTypeTag(typeExpression, ""); addJSDocTags(changes, sourceFile, parent, [typeTag]); } - else { + else if (!tryReplaceImportTypeNodeWithAutoImport(typeNode, changes, sourceFile, declaration, type, program, host, formatContext, preferences)) { changes.tryInsertTypeAnnotation(sourceFile, declaration, typeNode); } } } + function tryReplaceImportTypeNodeWithAutoImport(typeNode: TypeNode, changes: textChanges.ChangeTracker, sourceFile: SourceFile, declaration: textChanges.TypeAnnotatable, type: Type, program: Program, host: LanguageServiceHost, formatContext: formatting.FormatContext, preferences: UserPreferences): boolean { + if (isLiteralImportTypeNode(typeNode) && typeNode.qualifier && type.symbol) { + // Replace 'import("./a").SomeType' with 'SomeType' and an actual import if possible + const moduleSymbol = find(type.symbol.declarations, d => !!d.getSourceFile().externalModuleIndicator)?.getSourceFile().symbol; + // Symbol for the left-most thing after the dot + if (moduleSymbol) { + const symbol = getFirstIdentifier(typeNode.qualifier).symbol; + const action = getImportCompletionAction( + symbol, + moduleSymbol, + sourceFile, + symbol.name, + host, + program, + formatContext, + declaration.pos, + preferences, + ); + if (action.codeAction.changes.length && changes.tryInsertTypeAnnotation(sourceFile, declaration, createTypeReferenceNode(typeNode.qualifier, typeNode.typeArguments))) { + for (const change of action.codeAction.changes) { + const file = sourceFile.fileName === change.fileName ? sourceFile : Debug.assertDefined(program.getSourceFile(change.fileName)); + changes.pushRaw(file, change); + } + return true; + } + } + } + return false; + } + function annotateJSDocParameters(changes: textChanges.ChangeTracker, sourceFile: SourceFile, parameterInferences: readonly ParameterInference[], program: Program, host: LanguageServiceHost): void { const signature = parameterInferences.length && parameterInferences[0].declaration.parent; if (!signature) { @@ -1054,7 +1112,7 @@ namespace ts.codefix { } const returnType = combineFromUsage(combineUsages(calls.map(call => call.return_))); // TODO: GH#18217 - return checker.createSignature(/*declaration*/ undefined!, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false); + return checker.createSignature(/*declaration*/ undefined!, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, SignatureFlags.None); } function addCandidateType(usage: Usage, type: Type | undefined) { diff --git a/src/services/completions.ts b/src/services/completions.ts index 1c3288a3282..076cc32f374 100644 --- a/src/services/completions.ts +++ b/src/services/completions.ts @@ -338,6 +338,7 @@ namespace ts.Completions { ): CompletionEntry | undefined { let insertText: string | undefined; let replacementSpan: TextSpan | undefined; + const insertQuestionDot = origin && originIsNullableMember(origin); const useBraces = origin && originIsSymbolMember(origin) || needsConvertPropertyAccess; if (origin && originIsThisType(origin)) { @@ -780,7 +781,7 @@ namespace ts.Completions { sourceFile: SourceFile, isUncheckedFile: boolean, position: number, - preferences: Pick, + preferences: Pick, detailsEntryId: CompletionEntryIdentifier | undefined, host: LanguageServiceHost, ): CompletionData | Request | undefined { @@ -1000,6 +1001,7 @@ namespace ts.Completions { let completionKind = CompletionKind.None; let isNewIdentifierLocation = false; let keywordFilters = KeywordCompletionFilters.None; + // This also gets mutated in nested-functions after the return let symbols: Symbol[] = []; const symbolToOriginInfoMap: SymbolOriginInfoMap = []; const symbolToSortTextMap: SymbolSortTextMap = []; @@ -1115,8 +1117,17 @@ namespace ts.Completions { let type = typeChecker.getTypeOfSymbolAtLocation(symbol, node).getNonOptionalType(); let insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + const canCorrectToQuestionDot = + isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & NodeFlags.AwaitContext), insertQuestionDot); } @@ -1136,8 +1147,17 @@ namespace ts.Completions { let type = typeChecker.getTypeAtLocation(node).getNonOptionalType(); let insertQuestionDot = false; if (type.isNullableType()) { - insertQuestionDot = isRightOfDot && !isRightOfQuestionDot; - type = type.getNonNullableType(); + const canCorrectToQuestionDot = + isRightOfDot && + !isRightOfQuestionDot && + preferences.includeAutomaticOptionalChainCompletions !== false; + + if (canCorrectToQuestionDot || isRightOfQuestionDot) { + type = type.getNonNullableType(); + if (canCorrectToQuestionDot) { + insertQuestionDot = true; + } + } } addTypeProperties(type, !!(node.flags & NodeFlags.AwaitContext), insertQuestionDot); } @@ -1464,7 +1484,7 @@ namespace ts.Completions { } /** - * Gathers symbols that can be imported from other files, deduplicating along the way. Symbols can be “duplicates” + * Gathers symbols that can be imported from other files, de-duplicating along the way. Symbols can be "duplicates" * if re-exported from another module, e.g. `export { foo } from "./a"`. That syntax creates a fresh symbol, but * it’s just an alias to the first, and both have the same name, so we generally want to filter those aliases out, * if and only if the the first can be imported (it may be excluded due to package.json filtering in @@ -1548,7 +1568,7 @@ namespace ts.Completions { // Don't add another completion for `export =` of a symbol that's already global. // So in `declare namespace foo {} declare module "foo" { export = foo; }`, there will just be the global completion for `foo`. if (resolvedModuleSymbol !== moduleSymbol && - every(resolvedModuleSymbol.declarations, d => !!d.getSourceFile().externalModuleIndicator)) { + every(resolvedModuleSymbol.declarations, d => !!d.getSourceFile().externalModuleIndicator && !findAncestor(d, isGlobalScopeAugmentation))) { pushSymbol(resolvedModuleSymbol, moduleSymbol, /*skipFilter*/ true); } @@ -1760,7 +1780,7 @@ namespace ts.Completions { let existingMembers: readonly Declaration[] | undefined; if (objectLikeContainer.kind === SyntaxKind.ObjectLiteralExpression) { - const typeForObject = typeChecker.getContextualType(objectLikeContainer); + const typeForObject = typeChecker.getContextualType(objectLikeContainer, ContextFlags.Completion); if (!typeForObject) return GlobalsSearch.Fail; isNewIdentifierLocation = hasIndexSignature(typeForObject); typeMembers = getPropertiesForObjectExpression(typeForObject, objectLikeContainer, typeChecker); @@ -2406,6 +2426,8 @@ namespace ts.Completions { return isFunctionLikeBodyKeyword(kind) || kind === SyntaxKind.DeclareKeyword || kind === SyntaxKind.ModuleKeyword + || kind === SyntaxKind.TypeKeyword + || kind === SyntaxKind.NamespaceKeyword || isTypeKeyword(kind) && kind !== SyntaxKind.UndefinedKeyword; case KeywordCompletionFilters.FunctionLikeBodyKeywords: return isFunctionLikeBodyKeyword(kind); diff --git a/src/services/findAllReferences.ts b/src/services/findAllReferences.ts index 2db77a146f2..bd0e63561da 100644 --- a/src/services/findAllReferences.ts +++ b/src/services/findAllReferences.ts @@ -1395,8 +1395,10 @@ namespace ts.FindAllReferences.Core { || exportSpecifier.name.originalKeywordKind === SyntaxKind.DefaultKeyword; const exportKind = isDefaultExport ? ExportKind.Default : ExportKind.Named; const exportSymbol = Debug.assertDefined(exportSpecifier.symbol); - const exportInfo = Debug.assertDefined(getExportInfo(exportSymbol, exportKind, state.checker)); - searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + const exportInfo = getExportInfo(exportSymbol, exportKind, state.checker); + if (exportInfo) { + searchForImportsOfExport(referenceLocation, exportSymbol, exportInfo, state); + } } // At `export { x } from "foo"`, also search for the imported symbol `"foo".x`. diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.ts index 75720555f52..8a86cd7a65d 100644 --- a/src/services/formatting/rules.ts +++ b/src/services/formatting/rules.ts @@ -59,8 +59,8 @@ namespace ts.formatting { // in other cases there should be no space between '?' and next token rule("NoSpaceAfterQuestionMark", SyntaxKind.QuestionToken, anyToken, [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace), - rule("NoSpaceBeforeDot", anyToken, SyntaxKind.DotToken, [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace), - rule("NoSpaceAfterDot", SyntaxKind.DotToken, anyToken, [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace), + rule("NoSpaceBeforeDot", anyToken, [SyntaxKind.DotToken, SyntaxKind.QuestionDotToken], [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace), + rule("NoSpaceAfterDot", [SyntaxKind.DotToken, SyntaxKind.QuestionDotToken], anyToken, [isNonJsxSameLineTokenContext], RuleAction.DeleteSpace), rule("NoSpaceBetweenImportParenInImportType", SyntaxKind.ImportKeyword, SyntaxKind.OpenParenToken, [isNonJsxSameLineTokenContext, isImportTypeContext], RuleAction.DeleteSpace), diff --git a/src/services/jsDoc.ts b/src/services/jsDoc.ts index f5c86bcf9cb..56e0a0ae50e 100644 --- a/src/services/jsDoc.ts +++ b/src/services/jsDoc.ts @@ -158,25 +158,6 @@ namespace ts.JsDoc { } } - /** - * Iterates through 'array' by index and performs the callback on each element of array until the callback - * returns a truthy value, then returns that value. - * If no such value is found, the callback is applied to each element of array and undefined is returned. - */ - function forEachUnique(array: readonly T[] | undefined, callback: (element: T, index: number) => U): U | undefined { - if (array) { - for (let i = 0; i < array.length; i++) { - if (array.indexOf(array[i]) === i) { - const result = callback(array[i], i); - if (result) { - return result; - } - } - } - } - return undefined; - } - export function getJSDocTagNameCompletions(): CompletionEntry[] { return jsDocTagNameCompletionEntries || (jsDocTagNameCompletionEntries = map(jsDocTagNames, tagName => { return { diff --git a/src/services/services.ts b/src/services/services.ts index 6a1c721cbba..acd3688f332 100644 --- a/src/services/services.ts +++ b/src/services/services.ts @@ -452,9 +452,19 @@ namespace ts { isClass(): this is InterfaceType { return !!(getObjectFlags(this) & ObjectFlags.Class); } + /** + * This polyfills `referenceType.typeArguments` for API consumers + */ + get typeArguments() { + if (getObjectFlags(this) & ObjectFlags.Reference) { + return this.checker.getTypeArguments(this as Type as TypeReference); + } + return undefined; + } } class SignatureObject implements Signature { + flags: SignatureFlags; checker: TypeChecker; declaration!: SignatureDeclaration; typeParameters?: TypeParameter[]; @@ -464,8 +474,6 @@ namespace ts { resolvedTypePredicate: TypePredicate | undefined; minTypeArgumentCount!: number; minArgumentCount!: number; - hasRestParameter!: boolean; - hasLiteralTypes!: boolean; // Undefined is used to indicate the value has not been computed. If, after computing, the // symbol has no doc comment, then the empty array will be returned. @@ -475,9 +483,11 @@ namespace ts { // symbol has no doc comment, then the empty array will be returned. jsDocTags?: JSDocTagInfo[]; - constructor(checker: TypeChecker) { + constructor(checker: TypeChecker, flags: SignatureFlags) { this.checker = checker; + this.flags = flags; } + getDeclaration(): SignatureDeclaration { return this.declaration; } @@ -518,11 +528,11 @@ namespace ts { let doc = JsDoc.getJsDocCommentsFromDeclarations(declarations); if (doc.length === 0 || declarations.some(hasJSDocInheritDocTag)) { - for (const declaration of declarations) { + forEachUnique(declarations, declaration => { const inheritedDocs = findInheritedJSDocComments(declaration, declaration.symbol.name, checker!); // TODO: GH#18217 // TODO: GH#16312 Return a ReadonlyArray, avoid copying inheritedDocs if (inheritedDocs) doc = doc.length === 0 ? inheritedDocs.slice() : inheritedDocs.concat(lineBreakPart(), doc); - } + }); } return doc; } @@ -1629,12 +1639,12 @@ namespace ts { return NavigateTo.getNavigateToItems(sourceFiles, program.getTypeChecker(), cancellationToken, searchValue, maxResultCount, excludeDtsFiles); } - function getEmitOutput(fileName: string, emitOnlyDtsFiles = false) { + function getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean) { synchronizeHostData(); const sourceFile = getValidSourceFile(fileName); const customTransformers = host.getCustomTransformers && host.getCustomTransformers(); - return getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers); + return getFileEmitOutput(program, sourceFile, !!emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit); } // Signature help diff --git a/src/services/stringCompletions.ts b/src/services/stringCompletions.ts index 7e106ae54c4..b474f391049 100644 --- a/src/services/stringCompletions.ts +++ b/src/services/stringCompletions.ts @@ -204,7 +204,7 @@ namespace ts.Completions.StringCompletions { const candidates: Signature[] = []; checker.getResolvedSignature(argumentInfo.invocation, candidates, argumentInfo.argumentCount); const types = flatMap(candidates, candidate => { - if (!candidate.hasRestParameter && argumentInfo.argumentCount > candidate.parameters.length) return; + if (!signatureHasRestParameter(candidate) && argumentInfo.argumentCount > candidate.parameters.length) return; const type = checker.getParameterType(candidate, argumentInfo.argumentIndex); isNewIdentifier = isNewIdentifier || !!(type.flags & TypeFlags.String); return getStringLiteralTypes(type, uniques); diff --git a/src/services/symbolDisplay.ts b/src/services/symbolDisplay.ts index 0dc540dcaca..faff3620d62 100644 --- a/src/services/symbolDisplay.ts +++ b/src/services/symbolDisplay.ts @@ -237,7 +237,7 @@ namespace ts.SymbolDisplay { // get the signature from the declaration and write it const functionDeclaration = location.parent; // Use function declaration to write the signatures only if the symbol corresponding to this declaration - const locationIsSymbolDeclaration = find(symbol.declarations, declaration => + const locationIsSymbolDeclaration = symbol.declarations && find(symbol.declarations, declaration => declaration === (location.kind === SyntaxKind.ConstructorKeyword ? functionDeclaration.parent : functionDeclaration)); if (locationIsSymbolDeclaration) { diff --git a/src/services/textChanges.ts b/src/services/textChanges.ts index ad68a8ff5c8..07a75d884d9 100644 --- a/src/services/textChanges.ts +++ b/src/services/textChanges.ts @@ -248,6 +248,18 @@ namespace ts.textChanges { /** Public for tests only. Other callers should use `ChangeTracker.with`. */ constructor(private readonly newLineCharacter: string, private readonly formatContext: formatting.FormatContext) {} + public pushRaw(sourceFile: SourceFile, change: FileTextChanges) { + Debug.assertEqual(sourceFile.fileName, change.fileName); + for (const c of change.textChanges) { + this.changes.push({ + kind: ChangeKind.Text, + sourceFile, + text: c.newText, + range: createTextRangeFromSpan(c.span), + }); + } + } + public deleteRange(sourceFile: SourceFile, range: TextRange): void { this.changes.push({ kind: ChangeKind.Remove, sourceFile, range }); } @@ -383,12 +395,12 @@ namespace ts.textChanges { } /** Prefer this over replacing a node with another that has a type annotation, as it avoids reformatting the other parts of the node. */ - public tryInsertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): void { + public tryInsertTypeAnnotation(sourceFile: SourceFile, node: TypeAnnotatable, type: TypeNode): boolean { let endNode: Node | undefined; if (isFunctionLike(node)) { endNode = findChildOfKind(node, SyntaxKind.CloseParenToken, sourceFile); if (!endNode) { - if (!isArrowFunction(node)) return; // Function missing parentheses, give up + if (!isArrowFunction(node)) return false; // Function missing parentheses, give up // If no `)`, is an arrow function `x => x`, so use the end of the first parameter endNode = first(node.parameters); } @@ -398,6 +410,7 @@ namespace ts.textChanges { } this.insertNodeAt(sourceFile, endNode.end, type, { prefix: ": " }); + return true; } public tryInsertThisTypeAnnotation(sourceFile: SourceFile, node: ThisTypeAnnotatable, type: TypeNode): void { diff --git a/src/services/tsconfig.json b/src/services/tsconfig.json index 5c0e39f9f65..a75a96c961e 100644 --- a/src/services/tsconfig.json +++ b/src/services/tsconfig.json @@ -4,6 +4,7 @@ "outFile": "../../built/local/services.js" }, "references": [ + { "path": "../shims" }, { "path": "../compiler" }, { "path": "../jsTyping" } ], diff --git a/src/services/types.ts b/src/services/types.ts index 65544d5677d..21a92e169d8 100644 --- a/src/services/types.ts +++ b/src/services/types.ts @@ -68,6 +68,10 @@ namespace ts { isClass(): this is InterfaceType; } + export interface TypeReference { + typeArguments?: readonly Type[]; + } + export interface Signature { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; @@ -239,6 +243,8 @@ namespace ts { resolveTypeReferenceDirectives?(typeDirectiveNames: string[], containingFile: string, redirectedReference: ResolvedProjectReference | undefined, options: CompilerOptions): (ResolvedTypeReferenceDirective | undefined)[]; /* @internal */ hasInvalidatedResolution?: HasInvalidatedResolution; /* @internal */ hasChangedAutomaticTypeDirectiveNames?: boolean; + /* @internal */ + getGlobalTypingsCacheLocation?(): string | undefined; /* * Required for full import and type reference completions. @@ -387,7 +393,7 @@ namespace ts { organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; @@ -534,7 +540,7 @@ namespace ts { export interface FileTextChanges { fileName: string; - textChanges: TextChange[]; + textChanges: readonly TextChange[]; isNewFile?: boolean; } diff --git a/src/services/utilities.ts b/src/services/utilities.ts index cea78be7151..d0e75c5522f 100644 --- a/src/services/utilities.ts +++ b/src/services/utilities.ts @@ -1458,6 +1458,25 @@ namespace ts { export function documentSpansEqual(a: DocumentSpan, b: DocumentSpan): boolean { return a.fileName === b.fileName && textSpansEqual(a.textSpan, b.textSpan); } + + /** + * Iterates through 'array' by index and performs the callback on each element of array until the callback + * returns a truthy value, then returns that value. + * If no such value is found, the callback is applied to each element of array and undefined is returned. + */ + export function forEachUnique(array: readonly T[] | undefined, callback: (element: T, index: number) => U): U | undefined { + if (array) { + for (let i = 0; i < array.length; i++) { + if (array.indexOf(array[i]) === i) { + const result = callback(array[i], i); + if (result) { + return result; + } + } + } + } + return undefined; + } } // Display-part writer helpers diff --git a/src/shims/mapShim.ts b/src/shims/mapShim.ts new file mode 100644 index 00000000000..e0468ad43f2 --- /dev/null +++ b/src/shims/mapShim.ts @@ -0,0 +1,212 @@ +/* @internal */ +namespace ts { + // NOTE: Due to how the project-reference merging ends up working, `T` isn't considered referenced until `Map` merges with the definition + // in src/compiler/core.ts + // @ts-ignore + export interface Map { + // full type defined in ~/src/compiler/core.ts + } + + export function createMapShim(): new () => Map { + /** Create a MapLike with good performance. */ + function createDictionaryObject(): Record { + const map = Object.create(/*prototype*/ null); // eslint-disable-line no-null/no-null + + // Using 'delete' on an object causes V8 to put the object in dictionary mode. + // This disables creation of hidden classes, which are expensive when an object is + // constantly changing shape. + map.__ = undefined; + delete map.__; + + return map; + } + + interface MapEntry { + readonly key?: string; + value?: T; + + // Linked list references for iterators. + nextEntry?: MapEntry; + previousEntry?: MapEntry; + + /** + * Specifies if iterators should skip the next entry. + * This will be set when an entry is deleted. + * See https://github.com/Microsoft/TypeScript/pull/27292 for more information. + */ + skipNext?: boolean; + } + + class MapIterator { + private currentEntry?: MapEntry; + private selector: (key: string, value: T) => U; + + constructor(currentEntry: MapEntry, selector: (key: string, value: T) => U) { + this.currentEntry = currentEntry; + this.selector = selector; + } + + public next(): { value: U, done: false } | { value: never, done: true } { + // Navigate to the next entry. + while (this.currentEntry) { + const skipNext = !!this.currentEntry.skipNext; + this.currentEntry = this.currentEntry.nextEntry; + + if (!skipNext) { + break; + } + } + + if (this.currentEntry) { + return { value: this.selector(this.currentEntry.key!, this.currentEntry.value!), done: false }; + } + else { + return { value: undefined as never, done: true }; + } + } + } + + return class implements Map { + private data = createDictionaryObject>(); + public size = 0; + + // Linked list references for iterators. + // See https://github.com/Microsoft/TypeScript/pull/27292 + // for more information. + + /** + * The first entry in the linked list. + * Note that this is only a stub that serves as starting point + * for iterators and doesn't contain a key and a value. + */ + private readonly firstEntry: MapEntry; + private lastEntry: MapEntry; + + constructor() { + // Create a first (stub) map entry that will not contain a key + // and value but serves as starting point for iterators. + this.firstEntry = {}; + // When the map is empty, the last entry is the same as the + // first one. + this.lastEntry = this.firstEntry; + } + + get(key: string): T | undefined { + const entry = this.data[key] as MapEntry | undefined; + return entry && entry.value!; + } + + set(key: string, value: T): this { + if (!this.has(key)) { + this.size++; + + // Create a new entry that will be appended at the + // end of the linked list. + const newEntry: MapEntry = { + key, + value + }; + this.data[key] = newEntry; + + // Adjust the references. + const previousLastEntry = this.lastEntry; + previousLastEntry.nextEntry = newEntry; + newEntry.previousEntry = previousLastEntry; + this.lastEntry = newEntry; + } + else { + this.data[key].value = value; + } + + return this; + } + + has(key: string): boolean { + // eslint-disable-next-line no-in-operator + return key in this.data; + } + + delete(key: string): boolean { + if (this.has(key)) { + this.size--; + const entry = this.data[key]; + delete this.data[key]; + + // Adjust the linked list references of the neighbor entries. + const previousEntry = entry.previousEntry!; + previousEntry.nextEntry = entry.nextEntry; + if (entry.nextEntry) { + entry.nextEntry.previousEntry = previousEntry; + } + + // When the deleted entry was the last one, we need to + // adjust the lastEntry reference. + if (this.lastEntry === entry) { + this.lastEntry = previousEntry; + } + + // Adjust the forward reference of the deleted entry + // in case an iterator still references it. This allows us + // to throw away the entry, but when an active iterator + // (which points to the current entry) continues, it will + // navigate to the entry that originally came before the + // current one and skip it. + entry.previousEntry = undefined; + entry.nextEntry = previousEntry; + entry.skipNext = true; + + return true; + } + return false; + } + + clear(): void { + this.data = createDictionaryObject>(); + this.size = 0; + + // Reset the linked list. Note that we must adjust the forward + // references of the deleted entries to ensure iterators stuck + // in the middle of the list don't continue with deleted entries, + // but can continue with new entries added after the clear() + // operation. + const firstEntry = this.firstEntry; + let currentEntry = firstEntry.nextEntry; + while (currentEntry) { + const nextEntry = currentEntry.nextEntry; + currentEntry.previousEntry = undefined; + currentEntry.nextEntry = firstEntry; + currentEntry.skipNext = true; + + currentEntry = nextEntry; + } + firstEntry.nextEntry = undefined; + this.lastEntry = firstEntry; + } + + keys(): Iterator { + return new MapIterator(this.firstEntry, key => key); + } + + values(): Iterator { + return new MapIterator(this.firstEntry, (_key, value) => value); + } + + entries(): Iterator<[string, T]> { + return new MapIterator(this.firstEntry, (key, value) => [key, value] as [string, T]); + } + + forEach(action: (value: T, key: string) => void): void { + const iterator = this.entries(); + while (true) { + const iterResult = iterator.next(); + if (iterResult.done) { + break; + } + + const [key, value] = iterResult.value; + action(value, key); + } + } + }; + } +} \ No newline at end of file diff --git a/src/shims/tsconfig.json b/src/shims/tsconfig.json new file mode 100644 index 00000000000..cb058762fd6 --- /dev/null +++ b/src/shims/tsconfig.json @@ -0,0 +1,9 @@ +{ + "extends": "../tsconfig-base", + "compilerOptions": { + "outFile": "../../built/local/shims.js" + }, + "files": [ + "mapShim.ts" + ] +} diff --git a/src/testRunner/parallel/host.ts b/src/testRunner/parallel/host.ts index 89264224c13..0273ad7ec4e 100644 --- a/src/testRunner/parallel/host.ts +++ b/src/testRunner/parallel/host.ts @@ -147,7 +147,7 @@ namespace Harness.Parallel.Host { } cursor.hide(); - readline.moveCursor(process.stdout, -process.stdout.columns!, -this._lineCount); + readline.moveCursor(process.stdout, -process.stdout.columns, -this._lineCount); let lineCount = 0; const numProgressBars = this._progressBars.length; for (let i = 0; i < numProgressBars; i++) { @@ -156,7 +156,7 @@ namespace Harness.Parallel.Host { process.stdout.write(this._progressBars[i].text + os.EOL); } else { - readline.moveCursor(process.stdout, -process.stdout.columns!, +1); + readline.moveCursor(process.stdout, -process.stdout.columns, +1); } lineCount++; diff --git a/src/testRunner/tsconfig.json b/src/testRunner/tsconfig.json index 1892c4c4815..6c120e30349 100644 --- a/src/testRunner/tsconfig.json +++ b/src/testRunner/tsconfig.json @@ -14,6 +14,7 @@ ] }, "references": [ + { "path": "../shims", "prepend": true }, { "path": "../compiler", "prepend": true }, { "path": "../services", "prepend": true }, { "path": "../jsTyping", "prepend": true }, @@ -38,6 +39,7 @@ "unittests/services/extract/helpers.ts", "unittests/tsbuild/helpers.ts", + "../tsc/executeCommandLine.ts", "unittests/tsc/helpers.ts", "unittests/tscWatch/helpers.ts", "unittests/tsserver/helpers.ts", @@ -60,7 +62,7 @@ "unittests/publicApi.ts", "unittests/reuseProgramStructure.ts", "unittests/semver.ts", - "unittests/shimMap.ts", + "unittests/createMapShim.ts", "unittests/transform.ts", "unittests/config/commandLineParsing.ts", "unittests/config/configurationExtension.ts", @@ -98,6 +100,7 @@ "unittests/tsbuild/demo.ts", "unittests/tsbuild/emitDeclarationOnly.ts", "unittests/tsbuild/emptyFiles.ts", + "unittests/tsbuild/exitCodeOnBogusFile.ts", "unittests/tsbuild/graphOrdering.ts", "unittests/tsbuild/inferredTypeFromTransitiveModule.ts", "unittests/tsbuild/javascriptProjectEmit.ts", @@ -112,6 +115,8 @@ "unittests/tsbuild/watchEnvironment.ts", "unittests/tsbuild/watchMode.ts", "unittests/tsc/declarationEmit.ts", + "unittests/tsc/incremental.ts", + "unittests/tsc/listFilesOnly.ts", "unittests/tscWatch/consoleClearing.ts", "unittests/tscWatch/emit.ts", "unittests/tscWatch/emitAndErrorUpdates.ts", diff --git a/src/testRunner/unittests/config/commandLineParsing.ts b/src/testRunner/unittests/config/commandLineParsing.ts index 5c4998a750a..5792ee1a39c 100644 --- a/src/testRunner/unittests/config/commandLineParsing.ts +++ b/src/testRunner/unittests/config/commandLineParsing.ts @@ -446,6 +446,23 @@ namespace ts { }); }); + it("parse build with listFilesOnly ", () => { + // --lib es6 0.ts + assertParseResult(["--listFilesOnly"], + { + errors: [{ + messageText:"Unknown build option '--listFilesOnly'.", + category: Diagnostics.Unknown_build_option_0.category, + code: Diagnostics.Unknown_build_option_0.code, + file: undefined, + start: undefined, + length: undefined, + }], + projects: ["."], + buildOptions: {} + }); + }); + it("Parse multiple flags with input projects at the end", () => { // --lib es5,es2015.symbol.wellknown --target es5 0.ts assertParseResult(["--force", "--verbose", "src", "tests"], diff --git a/src/testRunner/unittests/shimMap.ts b/src/testRunner/unittests/createMapShim.ts similarity index 91% rename from src/testRunner/unittests/shimMap.ts rename to src/testRunner/unittests/createMapShim.ts index c3e94c0840c..c49e1cc63cc 100644 --- a/src/testRunner/unittests/shimMap.ts +++ b/src/testRunner/unittests/createMapShim.ts @@ -1,5 +1,5 @@ namespace ts { - describe("unittests:: shimMap", () => { + describe("unittests:: createMapShim", () => { function testMapIterationAddedValues(map: Map, useForEach: boolean): string { let resultString = ""; @@ -93,15 +93,15 @@ namespace ts { const nativeMapIteratorResult = testMapIterationAddedValues(nativeMap, /* useForEach */ false); assert.equal(nativeMapIteratorResult, expectedResult, "nativeMap-iterator"); - // Then, test the shimMap. - let localShimMap = new (shimMap())(); + // Then, test the map shim. + const MapShim = createMapShim(); // tslint:disable-line variable-name + let localShimMap = new MapShim(); const shimMapForEachResult = testMapIterationAddedValues(localShimMap, /* useForEach */ true); assert.equal(shimMapForEachResult, expectedResult, "shimMap-forEach"); - localShimMap = new (shimMap())(); + localShimMap = new MapShim(); const shimMapIteratorResult = testMapIterationAddedValues(localShimMap, /* useForEach */ false); assert.equal(shimMapIteratorResult, expectedResult, "shimMap-iterator"); - }); }); } diff --git a/src/testRunner/unittests/services/languageService.ts b/src/testRunner/unittests/services/languageService.ts index a5f38eb323b..d9a69dcd2e6 100644 --- a/src/testRunner/unittests/services/languageService.ts +++ b/src/testRunner/unittests/services/languageService.ts @@ -15,10 +15,9 @@ class Carousel extends Vue { "vue-class-component.d.ts": `import Vue from "./vue"; export function Component(x: Config): any;` }; - // Regression test for GH #18245 - bug in single line comment writer caused a debug assertion when attempting - // to write an alias to a module's default export was referrenced across files and had no default export - it("should be able to create a language service which can respond to deinition requests without throwing", () => { - const languageService = createLanguageService({ + + function createLanguageService() { + return ts.createLanguageService({ getCompilationSettings() { return {}; }, @@ -39,8 +38,45 @@ export function Component(x: Config): any;` return getDefaultLibFilePath(options); }, }); + } + // Regression test for GH #18245 - bug in single line comment writer caused a debug assertion when attempting + // to write an alias to a module's default export was referrenced across files and had no default export + it("should be able to create a language service which can respond to deinition requests without throwing", () => { + const languageService = createLanguageService(); const definitions = languageService.getDefinitionAtPosition("foo.ts", 160); // 160 is the latter `vueTemplateHtml` position expect(definitions).to.exist; // eslint-disable-line no-unused-expressions }); + + it("getEmitOutput on language service has way to force dts emit", () => { + const languageService = createLanguageService(); + assert.deepEqual( + languageService.getEmitOutput( + "foo.ts", + /*emitOnlyDtsFiles*/ true + ), + { + emitSkipped: true, + outputFiles: emptyArray, + exportedModulesFromDeclarationEmit: undefined + } + ); + + assert.deepEqual( + languageService.getEmitOutput( + "foo.ts", + /*emitOnlyDtsFiles*/ true, + /*forceDtsEmit*/ true + ), + { + emitSkipped: false, + outputFiles: [{ + name: "foo.d.ts", + text: "export {};\r\n", + writeByteOrderMark: false + }], + exportedModulesFromDeclarationEmit: undefined + } + ); + }); }); } diff --git a/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts b/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts index f621d956621..d1bcb321e52 100644 --- a/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts +++ b/src/testRunner/unittests/tsbuild/containerOnlyReferenced.ts @@ -9,40 +9,12 @@ namespace ts { projFs = undefined!; // Release the contents }); - function outputs(folder: string) { - return [ - `${folder}/index.js`, - `${folder}/index.d.ts`, - `${folder}/tsconfig.tsbuildinfo` - ]; - } - - it("verify that subsequent builds after initial build doesnt build anything", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - createSolutionBuilder(host, ["/src"], { verbose: true }).build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/src/folder/tsconfig.json", "src/src/folder2/tsconfig.json", "src/src/tsconfig.json", "src/tests/tsconfig.json", "src/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/src/folder/tsconfig.json", "src/src/folder/index.js"], - [Diagnostics.Building_project_0, "/src/src/folder/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/src/folder2/tsconfig.json", "src/src/folder2/index.js"], - [Diagnostics.Building_project_0, "/src/src/folder2/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/tests/tsconfig.json", "src/tests/index.js"], - [Diagnostics.Building_project_0, "/src/tests/tsconfig.json"], - ); - verifyOutputsPresent(fs, [ - ...outputs("/src/src/folder"), - ...outputs("/src/src/folder2"), - ...outputs("/src/tests"), - ]); - host.clearDiagnostics(); - createSolutionBuilder(host, ["/src"], { verbose: true }).build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/src/folder/tsconfig.json", "src/src/folder2/tsconfig.json", "src/src/tsconfig.json", "src/tests/tsconfig.json", "src/tsconfig.json"), - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/src/folder/tsconfig.json", "src/src/folder/index.ts", "src/src/folder/index.js"], - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/src/folder2/tsconfig.json", "src/src/folder2/index.ts", "src/src/folder2/index.js"], - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/tests/tsconfig.json", "src/tests/index.ts", "src/tests/index.js"], - ); + verifyTscIncrementalEdits({ + scenario: "containerOnlyReferenced", + subScenario: "verify that subsequent builds after initial build doesnt build anything", + fs: () => projFs, + commandLineArgs: ["--b", "/src", "--verbose"], + incrementalScenarios: [noChangeRun] }); }); } diff --git a/src/testRunner/unittests/tsbuild/demo.ts b/src/testRunner/unittests/tsbuild/demo.ts index c8a597368ff..18bc1eea89a 100644 --- a/src/testRunner/unittests/tsbuild/demo.ts +++ b/src/testRunner/unittests/tsbuild/demo.ts @@ -9,152 +9,41 @@ namespace ts { projFs = undefined!; // Release the contents }); - function coreOutputs(): string[] { - return [ - "/src/lib/core/utilities.js", - "/src/lib/core/utilities.d.ts", - "/src/lib/core/tsconfig.tsbuildinfo" - ]; - } - - function animalOutputs(): string[] { - return [ - "/src/lib/animals/animal.js", - "/src/lib/animals/animal.d.ts", - "/src/lib/animals/index.js", - "/src/lib/animals/index.d.ts", - "/src/lib/animals/dog.js", - "/src/lib/animals/dog.d.ts", - "/src/lib/animals/tsconfig.tsbuildinfo" - ]; - } - - function zooOutputs(): string[] { - return [ - "/src/lib/zoo/zoo.js", - "/src/lib/zoo/zoo.d.ts", - "/src/lib/zoo/tsconfig.tsbuildinfo" - ]; - } - - interface VerifyBuild { - modifyDiskLayout: (fs: vfs.FileSystem) => void; - expectedExitStatus: ExitStatus; - expectedDiagnostics: (fs: vfs.FileSystem) => fakes.ExpectedDiagnostic[]; - expectedOutputs: readonly string[]; - notExpectedOutputs: readonly string[]; - } - - function verifyBuild({ modifyDiskLayout, expectedExitStatus, expectedDiagnostics, expectedOutputs, notExpectedOutputs }: VerifyBuild) { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - modifyDiskLayout(fs); - const builder = createSolutionBuilder(host, ["/src/tsconfig.json"], { verbose: true }); - const exitStatus = builder.build(); - assert.equal(exitStatus, expectedExitStatus); - host.assertDiagnosticMessages(...expectedDiagnostics(fs)); - verifyOutputsPresent(fs, expectedOutputs); - verifyOutputsAbsent(fs, notExpectedOutputs); - } - - it("in master branch with everything setup correctly, reports no error", () => { - verifyBuild({ - modifyDiskLayout: noop, - expectedExitStatus: ExitStatus.Success, - expectedDiagnostics: () => [ - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/animals/tsconfig.json", "src/zoo/tsconfig.json", "src/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/core/tsconfig.json", "src/lib/core/utilities.js"], - [Diagnostics.Building_project_0, "/src/core/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/animals/tsconfig.json", "src/lib/animals/animal.js"], - [Diagnostics.Building_project_0, "/src/animals/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/zoo/tsconfig.json", "src/lib/zoo/zoo.js"], - [Diagnostics.Building_project_0, "/src/zoo/tsconfig.json"] - ], - expectedOutputs: [...coreOutputs(), ...animalOutputs(), ...zooOutputs()], - notExpectedOutputs: emptyArray - }); + verifyTsc({ + scenario: "demo", + subScenario: "in master branch with everything setup correctly and reports no error", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig.json", "--verbose"] }); - it("in circular branch reports the error about it by stopping build", () => { - verifyBuild({ - modifyDiskLayout: fs => replaceText( - fs, - "/src/core/tsconfig.json", - "}", - `}, + verifyTsc({ + scenario: "demo", + subScenario: "in circular branch reports the error about it by stopping build", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig.json", "--verbose"], + modifyFs: fs => replaceText( + fs, + "/src/core/tsconfig.json", + "}", + `}, "references": [ { "path": "../zoo" } ]` - ), - expectedExitStatus: ExitStatus.ProjectReferenceCycle_OutputsSkupped, - expectedDiagnostics: () => [ - getExpectedDiagnosticForProjectsInBuild("src/animals/tsconfig.json", "src/zoo/tsconfig.json", "src/core/tsconfig.json", "src/tsconfig.json"), - errorDiagnostic([ - Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, - [ - "/src/tsconfig.json", - "/src/core/tsconfig.json", - "/src/zoo/tsconfig.json", - "/src/animals/tsconfig.json" - ].join("\r\n") - ]) - ], - expectedOutputs: emptyArray, - notExpectedOutputs: [...coreOutputs(), ...animalOutputs(), ...zooOutputs()] - }); + ) }); - - it("in bad-ref branch reports the error about files not in rootDir at the import location", () => { - verifyBuild({ - modifyDiskLayout: fs => prependText( - fs, - "/src/core/utilities.ts", - `import * as A from '../animals'; + verifyTsc({ + scenario: "demo", + subScenario: "in bad-ref branch reports the error about files not in rootDir at the import location", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig.json", "--verbose"], + modifyFs: fs => prependText( + fs, + "/src/core/utilities.ts", + `import * as A from '../animals'; ` - ), - expectedExitStatus: ExitStatus.DiagnosticsPresent_OutputsSkipped, - expectedDiagnostics: fs => [ - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/animals/tsconfig.json", "src/zoo/tsconfig.json", "src/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/core/tsconfig.json", "src/lib/core/utilities.js"], - [Diagnostics.Building_project_0, "/src/core/tsconfig.json"], - { - message: [Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, "/src/animals/animal.ts", "/src/core"], - location: expectedLocationIndexOf(fs, "/src/animals/index.ts", `'./animal'`), - }, - { - message: [Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, "/src/animals/animal.ts", "/src/core/tsconfig.json"], - location: expectedLocationIndexOf(fs, "/src/animals/index.ts", `'./animal'`), - }, - { - message: [Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, "/src/animals/dog.ts", "/src/core"], - location: expectedLocationIndexOf(fs, "/src/animals/index.ts", `'./dog'`), - }, - { - message: [Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, "/src/animals/dog.ts", "/src/core/tsconfig.json"], - location: expectedLocationIndexOf(fs, "/src/animals/index.ts", `'./dog'`), - }, - { - message: [Diagnostics._0_is_declared_but_its_value_is_never_read, "A"], - location: expectedLocationIndexOf(fs, "/src/core/utilities.ts", `import * as A from '../animals';`), - }, - { - message: [Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, "/src/animals/index.ts", "/src/core"], - location: expectedLocationIndexOf(fs, "/src/core/utilities.ts", `'../animals'`), - }, - { - message: [Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, "/src/animals/index.ts", "/src/core/tsconfig.json"], - location: expectedLocationIndexOf(fs, "/src/core/utilities.ts", `'../animals'`), - }, - [Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, "src/animals/tsconfig.json", "src/core"], - [Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, "/src/animals/tsconfig.json", "/src/core"], - [Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built, "src/zoo/tsconfig.json", "src/animals"], - [Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built, "/src/zoo/tsconfig.json", "/src/animals"], - ], - expectedOutputs: emptyArray, - notExpectedOutputs: [...coreOutputs(), ...animalOutputs(), ...zooOutputs()] - }); + ) }); }); } diff --git a/src/testRunner/unittests/tsbuild/emptyFiles.ts b/src/testRunner/unittests/tsbuild/emptyFiles.ts index 6e09b5871f9..ffd9429a344 100644 --- a/src/testRunner/unittests/tsbuild/emptyFiles.ts +++ b/src/testRunner/unittests/tsbuild/emptyFiles.ts @@ -1,40 +1,25 @@ namespace ts { - const projFs = loadProjectFromDisk("tests/projects/empty-files"); - - const allExpectedOutputs = [ - "/src/core/index.js", - "/src/core/index.d.ts", - "/src/core/index.d.ts.map", - ]; - describe("unittests:: tsbuild - empty files option in tsconfig", () => { - it("has empty files diagnostic when files is empty and no references are provided", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/no-references"], { dry: false, force: false, verbose: false }); - - host.clearDiagnostics(); - builder.build(); - host.assertDiagnosticMessages({ - message: [Diagnostics.The_files_list_in_config_file_0_is_empty, "/src/no-references/tsconfig.json"], - location: expectedLocationLastIndexOf(fs, "/src/no-references/tsconfig.json", "[]"), - }); - - // Check for outputs to not be written. - verifyOutputsAbsent(fs, allExpectedOutputs); + let projFs: vfs.FileSystem; + before(() => { + projFs = loadProjectFromDisk("tests/projects/empty-files"); + }); + after(() => { + projFs = undefined!; }); - it("does not have empty files diagnostic when files is empty and references are provided", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/with-references"], { dry: false, force: false, verbose: false }); + verifyTsc({ + scenario: "emptyFiles", + subScenario: "has empty files diagnostic when files is empty and no references are provided", + fs: () => projFs, + commandLineArgs: ["--b", "/src/no-references"], + }); - host.clearDiagnostics(); - builder.build(); - host.assertDiagnosticMessages(/*empty*/); - - // Check for outputs to be written. - verifyOutputsPresent(fs, allExpectedOutputs); + verifyTsc({ + scenario: "emptyFiles", + subScenario: "does not have empty files diagnostic when files is empty and references are provided", + fs: () => projFs, + commandLineArgs: ["--b", "/src/with-references"], }); }); } diff --git a/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts b/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts new file mode 100644 index 00000000000..09821d76e5e --- /dev/null +++ b/src/testRunner/unittests/tsbuild/exitCodeOnBogusFile.ts @@ -0,0 +1,11 @@ +namespace ts { + // https://github.com/microsoft/TypeScript/issues/33849 + describe("unittests:: tsbuild:: exitCodeOnBogusFile:: test exit code", () => { + verifyTsc({ + scenario: "exitCodeOnBogusFile", + subScenario: `test exit code`, + fs: () => loadProjectFromFiles({}, symbolLibContent), + commandLineArgs: ["-b", "bogus.json"] + }); + }); +} diff --git a/src/testRunner/unittests/tsbuild/helpers.ts b/src/testRunner/unittests/tsbuild/helpers.ts index b21c60a8617..cc5dd3f8556 100644 --- a/src/testRunner/unittests/tsbuild/helpers.ts +++ b/src/testRunner/unittests/tsbuild/helpers.ts @@ -228,7 +228,7 @@ interface Symbol { if (section.kind !== BundleFileSectionKind.Prepend) { writeTextOfSection(section.pos, section.end); } - else { + else if (section.texts.length > 0) { Debug.assert(section.pos === first(section.texts).pos); Debug.assert(section.end === last(section.texts).end); for (const text of section.texts) { @@ -237,6 +237,9 @@ interface Symbol { writeTextOfSection(text.pos, text.end); } } + else { + Debug.assert(section.pos === section.end); + } } baselineRecorder.WriteLine("======================================================================"); @@ -276,6 +279,7 @@ interface Symbol { buildKind: BuildKind; modifyFs: (fs: vfs.FileSystem) => void; subScenario?: string; + commandLineArgs?: readonly string[]; } export interface VerifyTsBuildInput extends TscCompile { @@ -287,7 +291,7 @@ interface Symbol { baselineSourceMap, modifyFs, baselineReadFileCalls, incrementalScenarios }: VerifyTsBuildInput) { - describe(`tsc --b ${scenario}:: ${subScenario}`, () => { + describe(`tsc ${commandLineArgs.join(" ")} ${scenario}:: ${subScenario}`, () => { let tick: () => void; let sys: TscCompileSystem; before(() => { @@ -315,7 +319,12 @@ interface Symbol { verifyTscBaseline(() => sys); }); - for (const { buildKind, modifyFs, subScenario: incrementalSubScenario } of incrementalScenarios) { + for (const { + buildKind, + modifyFs, + subScenario: incrementalSubScenario, + commandLineArgs: incrementalCommandLineArgs + } of incrementalScenarios) { describe(incrementalSubScenario || buildKind, () => { let newSys: TscCompileSystem; before(() => { @@ -326,7 +335,7 @@ interface Symbol { subScenario: incrementalSubScenario || subScenario, buildKind, fs: () => sys.vfs, - commandLineArgs, + commandLineArgs: incrementalCommandLineArgs || commandLineArgs, modifyFs: fs => { tick(); modifyFs(fs); diff --git a/src/testRunner/unittests/tsbuild/missingExtendedFile.ts b/src/testRunner/unittests/tsbuild/missingExtendedFile.ts index 7fa3352da26..398b38fdbea 100644 --- a/src/testRunner/unittests/tsbuild/missingExtendedFile.ts +++ b/src/testRunner/unittests/tsbuild/missingExtendedFile.ts @@ -1,17 +1,17 @@ namespace ts { describe("unittests:: tsbuild:: when tsconfig extends the missing file", () => { - it("unittests:: tsbuild - when tsconfig extends the missing file", () => { - const projFs = loadProjectFromDisk("tests/projects/missingExtendedConfig"); - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/tsconfig.json"], {}); - builder.build(); - host.assertDiagnosticMessages( - errorDiagnostic([Diagnostics.The_specified_path_does_not_exist_Colon_0, "/src/foobar.json"]), - errorDiagnostic([Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, "/src/tsconfig.first.json", "[\"**/*\"]", "[]"]), - errorDiagnostic([Diagnostics.The_specified_path_does_not_exist_Colon_0, "/src/foobar.json"]), - errorDiagnostic([Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2, "/src/tsconfig.second.json", "[\"**/*\"]", "[]"]) - ); + let projFs: vfs.FileSystem; + before(() => { + projFs = loadProjectFromDisk("tests/projects/missingExtendedConfig"); + }); + after(() => { + projFs = undefined!; + }); + verifyTsc({ + scenario: "missingExtendedConfig", + subScenario: "when tsconfig extends the missing file", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig.json"], }); }); } diff --git a/src/testRunner/unittests/tsbuild/outFile.ts b/src/testRunner/unittests/tsbuild/outFile.ts index 20cbe05a3c1..c352481979c 100644 --- a/src/testRunner/unittests/tsbuild/outFile.ts +++ b/src/testRunner/unittests/tsbuild/outFile.ts @@ -56,11 +56,6 @@ namespace ts { ] ]; const relSources = sources.map(([config, sources]) => [relName(config), sources.map(relName)]) as any as [Sources, Sources, Sources]; - let expectedOutputFiles = [ - ...outputFiles[project.first], - ...outputFiles[project.second], - ...outputFiles[project.third] - ]; let initialExpectedDiagnostics: readonly fakes.ExpectedDiagnostic[] = [ getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]), [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relSources[project.first][source.config], relOutputFiles[project.first][ext.js]], @@ -75,7 +70,6 @@ namespace ts { }); after(() => { outFileFs = undefined!; - expectedOutputFiles = undefined!; initialExpectedDiagnostics = undefined!; }); @@ -166,71 +160,37 @@ namespace ts { baselineOnly: true }); - it("clean projects", () => { + function getOutFileFsAfterBuild() { const fs = outFileFs.shadow(); - const expectedOutputs = [ - ...outputFiles[project.first], - ...outputFiles[project.second], - ...outputFiles[project.third] - ]; const host = fakes.SolutionBuilderHost.create(fs); const builder = createSolutionBuilder(host); builder.build(); - host.assertDiagnosticMessages(...initialExpectedDiagnostics); - // Verify they exist - verifyOutputsPresent(fs, expectedOutputs); - host.clearDiagnostics(); - builder.clean(); - host.assertDiagnosticMessages(/*none*/); - // Verify they are gone - verifyOutputsAbsent(fs, expectedOutputs); - // Subsequent clean shouldn't throw / etc - builder.clean(); + fs.makeReadonly(); + return fs; + } + + verifyTscIncrementalEdits({ + scenario: "outFile", + subScenario: "clean projects", + fs: getOutFileFsAfterBuild, + commandLineArgs: ["--b", "/src/third", "--clean"], + incrementalScenarios: [noChangeRun] }); - it("verify buildInfo absence results in new build", () => { - const { fs, tick } = getFsWithTime(outFileFs); - const expectedOutputs = [ - ...outputFiles[project.first], - ...outputFiles[project.second], - ...outputFiles[project.third] - ]; - const host = fakes.SolutionBuilderHost.create(fs); - let builder = createSolutionBuilder(host); - builder.build(); - host.assertDiagnosticMessages(...initialExpectedDiagnostics); - // Verify they exist - verifyOutputsPresent(fs, expectedOutputs); - // Delete bundle info - host.clearDiagnostics(); - - tick(); - host.deleteFile(outputFiles[project.first][ext.buildinfo]); - tick(); - - builder = createSolutionBuilder(host); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relSources[project.first][source.config], relOutputFiles[project.first][ext.buildinfo]], - [Diagnostics.Building_project_0, sources[project.first][source.config]], - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, relSources[project.second][source.config], relSources[project.second][source.ts][part.one], relOutputFiles[project.second][ext.js]], - [Diagnostics.Project_0_is_out_of_date_because_output_of_its_dependency_1_has_changed, relSources[project.third][source.config], "src/first"], - [Diagnostics.Updating_output_of_project_0, sources[project.third][source.config]], - [Diagnostics.Updating_unchanged_output_timestamps_of_project_0, sources[project.third][source.config]], - ); + verifyTsc({ + scenario: "outFile", + subScenario: "verify buildInfo absence results in new build", + fs: getOutFileFsAfterBuild, + commandLineArgs: ["--b", "/src/third", "--verbose"], + modifyFs: fs => fs.unlinkSync(outputFiles[project.first][ext.buildinfo]), }); - it("verify that if incremental is set to false, tsbuildinfo is not generated", () => { - const fs = outFileFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - replaceText(fs, sources[project.third][source.config], `"composite": true,`, ""); - const builder = createSolutionBuilder(host); - builder.build(); - host.assertDiagnosticMessages(...initialExpectedDiagnostics); - // Verify they exist - without tsbuildinfo for third project - verifyOutputsPresent(fs, expectedOutputFiles.slice(0, expectedOutputFiles.length - 2)); - verifyOutputsAbsent(fs, [outputFiles[project.third][ext.buildinfo]]); + verifyTsc({ + scenario: "outFile", + subScenario: "tsbuildinfo is not generated when incremental is set to false", + fs: () => outFileFs, + commandLineArgs: ["--b", "/src/third", "--verbose"], + modifyFs: fs => replaceText(fs, sources[project.third][source.config], `"composite": true,`, ""), }); it("rebuilds completely when version in tsbuildinfo doesnt match ts version", () => { @@ -682,6 +642,40 @@ ${internal} enum internalEnum { a, b, c }`); ignoreDtsUnchanged: true, baselineOnly: true }); + + verifyOutFileScenario({ + subScenario: "stripInternal when prepend is completely internal", + baselineOnly: true, + ignoreDtsChanged: true, + ignoreDtsUnchanged: true, + modifyFs: fs => { + fs.writeFileSync(sources[project.first][source.ts][part.one], "/* @internal */ const A = 1;"); + fs.writeFileSync(sources[project.third][source.ts][part.one], "const B = 2;"); + fs.writeFileSync(sources[project.first][source.config], JSON.stringify({ + compilerOptions: { + composite: true, + declaration: true, + declarationMap: true, + skipDefaultLibCheck: true, + sourceMap: true, + outFile: "./bin/first-output.js" + }, + files: [sources[project.first][source.ts][part.one]] + })); + fs.writeFileSync(sources[project.third][source.config], JSON.stringify({ + compilerOptions: { + composite: true, + declaration: true, + declarationMap: false, + stripInternal: true, + sourceMap: true, + outFile: "./thirdjs/output/third-output.js" + }, + references: [{ path: "../first", prepend: true }], + files: [sources[project.third][source.ts][part.one]] + })); + } + }); }); describe("empty source files", () => { @@ -713,44 +707,26 @@ ${internal} enum internalEnum { a, b, c }`); }); }); - it("non module projects without prepend", () => { - const fs = outFileFs.shadow(); - // No prepend - replaceText(fs, sources[project.third][source.config], `{ "path": "../first", "prepend": true }`, `{ "path": "../first" }`); - replaceText(fs, sources[project.third][source.config], `{ "path": "../second", "prepend": true }`, `{ "path": "../second" }`); + verifyTsc({ + scenario: "outFile", + subScenario: "non module projects without prepend", + fs: () => outFileFs, + commandLineArgs: ["--b", "/src/third", "--verbose"], + modifyFs: fs => { + // No prepend + replaceText(fs, sources[project.third][source.config], `{ "path": "../first", "prepend": true }`, `{ "path": "../first" }`); + replaceText(fs, sources[project.third][source.config], `{ "path": "../second", "prepend": true }`, `{ "path": "../second" }`); - // Non Modules - replaceText(fs, sources[project.first][source.config], `"composite": true,`, `"composite": true, "module": "none",`); - replaceText(fs, sources[project.second][source.config], `"composite": true,`, `"composite": true, "module": "none",`); - replaceText(fs, sources[project.third][source.config], `"composite": true,`, `"composite": true, "module": "none",`); + // Non Modules + replaceText(fs, sources[project.first][source.config], `"composite": true,`, `"composite": true, "module": "none",`); + replaceText(fs, sources[project.second][source.config], `"composite": true,`, `"composite": true, "module": "none",`); + replaceText(fs, sources[project.third][source.config], `"composite": true,`, `"composite": true, "module": "none",`); - // Own file emit - replaceText(fs, sources[project.first][source.config], `"outFile": "./bin/first-output.js",`, ""); - replaceText(fs, sources[project.second][source.config], `"outFile": "../2/second-output.js",`, ""); - replaceText(fs, sources[project.third][source.config], `"outFile": "./thirdjs/output/third-output.js",`, ""); - - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild(relSources[project.first][source.config], relSources[project.second][source.config], relSources[project.third][source.config]), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relSources[project.first][source.config], "src/first/first_PART1.js"], - [Diagnostics.Building_project_0, sources[project.first][source.config]], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relSources[project.second][source.config], "src/second/second_part1.js"], - [Diagnostics.Building_project_0, sources[project.second][source.config]], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, relSources[project.third][source.config], "src/third/third_part1.js"], - [Diagnostics.Building_project_0, sources[project.third][source.config]] - ); - const expectedOutputFiles = flatMap(sources, ([config, ts]) => [ - removeFileExtension(config) + Extension.TsBuildInfo, - ...flatMap(ts, f => [ - removeFileExtension(f) + Extension.Js, - removeFileExtension(f) + Extension.Js + ".map", - removeFileExtension(f) + Extension.Dts, - removeFileExtension(f) + Extension.Dts + ".map", - ]) - ]); - verifyOutputsPresent(fs, expectedOutputFiles); + // Own file emit + replaceText(fs, sources[project.first][source.config], `"outFile": "./bin/first-output.js",`, ""); + replaceText(fs, sources[project.second][source.config], `"outFile": "../2/second-output.js",`, ""); + replaceText(fs, sources[project.third][source.config], `"outFile": "./thirdjs/output/third-output.js",`, ""); + }, }); }); } diff --git a/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts b/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts index d81e5f3f947..bd78954780a 100644 --- a/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts +++ b/src/testRunner/unittests/tsbuild/referencesWithRootDirInParent.ts @@ -9,113 +9,53 @@ namespace ts { projFs = undefined!; // Release the contents }); - it("verify that it builds correctly", () => { - const allExpectedOutputs = [ - "/src/dist/other/other.js", "/src/dist/other/other.d.ts", - "/src/dist/main/a.js", "/src/dist/main/a.d.ts", - "/src/dist/main/b.js", "/src/dist/main/b.d.ts" - ]; - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/src/main", "/src/src/other"], {}); - builder.build(); - host.assertDiagnosticMessages(/*empty*/); - verifyOutputsPresent(fs, allExpectedOutputs); + verifyTsc({ + scenario: "projectReferenceWithRootDirInParent", + subScenario: "builds correctly", + fs: () => projFs, + commandLineArgs: ["--b", "/src/src/main", "/src/src/other"], }); - it("verify that it reports error for same .tsbuildinfo file because no rootDir in the base", () => { - const allExpectedOutputs = [ - "/src/dist/other.js", "/src/dist/other.d.ts", - "/src/dist/tsconfig.tsbuildinfo" - ]; - const missingOutputs = [ - "/src/dist/a.js", "/src/dist/a.d.ts", - "/src/dist/b.js", "/src/dist/b.d.ts" - ]; - const fs = projFs.shadow(); - replaceText(fs, "/src/tsconfig.base.json", `"rootDir": "./src/",`, ""); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/src/main"], { verbose: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/src/other/tsconfig.json", "src/src/main/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/src/other/tsconfig.json", "src/dist/other.js"], - [Diagnostics.Building_project_0, "/src/src/other/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/src/main/tsconfig.json", "src/dist/a.js"], - [Diagnostics.Building_project_0, "/src/src/main/tsconfig.json"], - { - message: [Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, "/src/dist/tsconfig.tsbuildinfo", "/src/src/other"], - location: expectedLocationIndexOf(fs, "/src/src/main/tsconfig.json", `{ "path": "../other" }`), - } - ); - verifyOutputsPresent(fs, allExpectedOutputs); - verifyOutputsAbsent(fs, missingOutputs); + verifyTsc({ + scenario: "projectReferenceWithRootDirInParent", + subScenario: "reports error for same tsbuildinfo file because no rootDir in the base", + fs: () => projFs, + commandLineArgs: ["--b", "/src/src/main", "--verbose"], + modifyFs: fs => replaceText(fs, "/src/tsconfig.base.json", `"rootDir": "./src/",`, ""), }); - it("verify that it reports error for same .tsbuildinfo file", () => { - const allExpectedOutputs = [ - "/src/dist/other.js", "/src/dist/other.d.ts", - "/src/dist/tsconfig.tsbuildinfo" - ]; - const missingOutputs = [ - "/src/dist/a.js", "/src/dist/a.d.ts", - "/src/dist/b.js", "/src/dist/b.d.ts" - ]; - const fs = projFs.shadow(); - fs.writeFileSync("/src/src/main/tsconfig.json", JSON.stringify({ - compilerOptions: { composite: true, outDir: "../../dist/" }, - references: [{ path: "../other" }] - })); - fs.writeFileSync("/src/src/other/tsconfig.json", JSON.stringify({ - compilerOptions: { composite: true, outDir: "../../dist/" }, - })); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/src/main"], { verbose: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/src/other/tsconfig.json", "src/src/main/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/src/other/tsconfig.json", "src/dist/other.js"], - [Diagnostics.Building_project_0, "/src/src/other/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/src/main/tsconfig.json", "src/dist/a.js"], - [Diagnostics.Building_project_0, "/src/src/main/tsconfig.json"], - { - message: [Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, "/src/dist/tsconfig.tsbuildinfo", "/src/src/other"], - location: expectedLocationIndexOf(fs, "/src/src/main/tsconfig.json", `{"path":"../other"}`), - } - ); - verifyOutputsPresent(fs, allExpectedOutputs); - verifyOutputsAbsent(fs, missingOutputs); + verifyTsc({ + scenario: "projectReferenceWithRootDirInParent", + subScenario: "reports error for same tsbuildinfo file", + fs: () => projFs, + commandLineArgs: ["--b", "/src/src/main", "--verbose"], + modifyFs: fs => { + fs.writeFileSync("/src/src/main/tsconfig.json", JSON.stringify({ + compilerOptions: { composite: true, outDir: "../../dist/" }, + references: [{ path: "../other" }] + })); + fs.writeFileSync("/src/src/other/tsconfig.json", JSON.stringify({ + compilerOptions: { composite: true, outDir: "../../dist/" }, + })); + }, }); - it("verify that it reports no error when .tsbuildinfo differ", () => { - const allExpectedOutputs = [ - "/src/dist/other.js", "/src/dist/other.d.ts", - "/src/dist/tsconfig.main.tsbuildinfo", - "/src/dist/a.js", "/src/dist/a.d.ts", - "/src/dist/b.js", "/src/dist/b.d.ts", - "/src/dist/tsconfig.other.tsbuildinfo" - ]; - const fs = projFs.shadow(); - fs.renameSync("/src/src/main/tsconfig.json", "/src/src/main/tsconfig.main.json"); - fs.renameSync("/src/src/other/tsconfig.json", "/src/src/other/tsconfig.other.json"); - fs.writeFileSync("/src/src/main/tsconfig.main.json", JSON.stringify({ - compilerOptions: { composite: true, outDir: "../../dist/" }, - references: [{ path: "../other/tsconfig.other.json" }] - })); - fs.writeFileSync("/src/src/other/tsconfig.other.json", JSON.stringify({ - compilerOptions: { composite: true, outDir: "../../dist/" }, - })); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/src/main/tsconfig.main.json"], { verbose: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/src/other/tsconfig.other.json", "src/src/main/tsconfig.main.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/src/other/tsconfig.other.json", "src/dist/other.js"], - [Diagnostics.Building_project_0, "/src/src/other/tsconfig.other.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/src/main/tsconfig.main.json", "src/dist/a.js"], - [Diagnostics.Building_project_0, "/src/src/main/tsconfig.main.json"] - ); - verifyOutputsPresent(fs, allExpectedOutputs); + verifyTsc({ + scenario: "projectReferenceWithRootDirInParent", + subScenario: "reports no error when tsbuildinfo differ", + fs: () => projFs, + commandLineArgs: ["--b", "/src/src/main/tsconfig.main.json", "--verbose"], + modifyFs: fs => { + fs.renameSync("/src/src/main/tsconfig.json", "/src/src/main/tsconfig.main.json"); + fs.renameSync("/src/src/other/tsconfig.json", "/src/src/other/tsconfig.other.json"); + fs.writeFileSync("/src/src/main/tsconfig.main.json", JSON.stringify({ + compilerOptions: { composite: true, outDir: "../../dist/" }, + references: [{ path: "../other/tsconfig.other.json" }] + })); + fs.writeFileSync("/src/src/other/tsconfig.other.json", JSON.stringify({ + compilerOptions: { composite: true, outDir: "../../dist/" }, + })); + }, }); }); } diff --git a/src/testRunner/unittests/tsbuild/resolveJsonModule.ts b/src/testRunner/unittests/tsbuild/resolveJsonModule.ts index 4d36bab67ba..3d1d8c3549d 100644 --- a/src/testRunner/unittests/tsbuild/resolveJsonModule.ts +++ b/src/testRunner/unittests/tsbuild/resolveJsonModule.ts @@ -1,7 +1,6 @@ namespace ts { describe("unittests:: tsbuild:: with resolveJsonModule option on project resolveJsonModuleAndComposite", () => { let projFs: vfs.FileSystem; - const allExpectedOutputs = ["/src/dist/src/index.js", "/src/dist/src/index.d.ts", "/src/dist/src/hello.json"]; before(() => { projFs = loadProjectFromDisk("tests/projects/resolveJsonModuleAndComposite"); }); @@ -10,108 +9,64 @@ namespace ts { projFs = undefined!; // Release the contents }); - function verifyProjectWithResolveJsonModule(configFile: string, ...expectedDiagnosticMessages: fakes.ExpectedDiagnostic[]) { - const fs = projFs.shadow(); - verifyProjectWithResolveJsonModuleWithFs(fs, configFile, allExpectedOutputs, ...expectedDiagnosticMessages); - } - - function verifyProjectWithResolveJsonModuleWithFs(fs: vfs.FileSystem, configFile: string, allExpectedOutputs: readonly string[], ...expectedDiagnosticMessages: fakes.ExpectedDiagnostic[]) { - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, [configFile], { dry: false, force: false, verbose: false }); - builder.build(); - host.assertDiagnosticMessages(...expectedDiagnosticMessages); - if (!expectedDiagnosticMessages.length) { - // Check for outputs. Not an exhaustive list - verifyOutputsPresent(fs, allExpectedOutputs); - } - } - - it("with resolveJsonModule and include only", () => { - verifyProjectWithResolveJsonModule( - "/src/tsconfig_withInclude.json", - { - message: [ - Diagnostics.File_0_is_not_listed_within_the_file_list_of_project_1_Projects_must_list_all_files_or_use_an_include_pattern, - "/src/src/hello.json", - "/src/tsconfig_withInclude.json" - ], - location: expectedLocationIndexOf(projFs, "/src/src/index.ts", `"./hello.json"`) - } - ); + verifyTsc({ + scenario: "resolveJsonModule", + subScenario: "include only", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig_withInclude.json"], }); - it("with resolveJsonModule and include of *.json along with other include", () => { - verifyProjectWithResolveJsonModule("/src/tsconfig_withIncludeOfJson.json"); + verifyTsc({ + scenario: "resolveJsonModule", + subScenario: "include of json along with other include", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig_withIncludeOfJson.json"], }); - it("with resolveJsonModule and include of *.json along with other include and file name matches ts file", () => { - const fs = projFs.shadow(); - fs.rimrafSync("/src/src/hello.json"); - fs.writeFileSync("/src/src/index.json", JSON.stringify({ hello: "world" })); - fs.writeFileSync("/src/src/index.ts", `import hello from "./index.json" + verifyTsc({ + scenario: "resolveJsonModule", + subScenario: "include of json along with other include and file name matches ts file", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig_withIncludeOfJson.json"], + modifyFs: fs => { + fs.rimrafSync("/src/src/hello.json"); + fs.writeFileSync("/src/src/index.json", JSON.stringify({ hello: "world" })); + fs.writeFileSync("/src/src/index.ts", `import hello from "./index.json" export default hello.hello`); - const allExpectedOutputs = ["/src/dist/src/index.js", "/src/dist/src/index.d.ts", "/src/dist/src/index.json"]; - verifyProjectWithResolveJsonModuleWithFs( - fs, - "/src/tsconfig_withIncludeOfJson.json", - allExpectedOutputs, - errorDiagnostic([Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, "/src/dist/src/index.d.ts"]) - ); + }, }); - it("with resolveJsonModule and files containing json file", () => { - verifyProjectWithResolveJsonModule("/src/tsconfig_withFiles.json"); + verifyTsc({ + scenario: "resolveJsonModule", + subScenario: "files containing json file", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig_withFiles.json"], }); - it("with resolveJsonModule and include and files", () => { - verifyProjectWithResolveJsonModule("/src/tsconfig_withIncludeAndFiles.json"); + verifyTsc({ + scenario: "resolveJsonModule", + subScenario: "include and files", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig_withIncludeAndFiles.json"], }); - it("with resolveJsonModule and sourceMap", () => { - const { fs, tick } = getFsWithTime(projFs); - const configFile = "src/tsconfig_withFiles.json"; - replaceText(fs, configFile, `"composite": true,`, `"composite": true, "sourceMap": true,`); - const host = fakes.SolutionBuilderHost.create(fs); - let builder = createSolutionBuilder(host, [configFile], { verbose: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild(configFile), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, configFile, "src/dist/src/index.js"], - [Diagnostics.Building_project_0, `/${configFile}`] - ); - verifyOutputsPresent(fs, [...allExpectedOutputs, "/src/dist/src/index.js.map"]); - host.clearDiagnostics(); - builder = createSolutionBuilder(host, [configFile], { verbose: true }); - tick(); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild(configFile), - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, configFile, "src/src/index.ts", "src/dist/src/index.js"] - ); + verifyTscIncrementalEdits({ + scenario: "resolveJsonModule", + subScenario: "sourcemap", + fs: () => projFs, + commandLineArgs: ["--b", "src/tsconfig_withFiles.json", "--verbose"], + modifyFs: fs => replaceText(fs, "src/tsconfig_withFiles.json", `"composite": true,`, `"composite": true, "sourceMap": true,`), + incrementalScenarios: [noChangeRun] }); - it("with resolveJsonModule and without outDir", () => { - const { fs, tick } = getFsWithTime(projFs); - const configFile = "src/tsconfig_withFiles.json"; - replaceText(fs, configFile, `"outDir": "dist",`, ""); - const host = fakes.SolutionBuilderHost.create(fs); - let builder = createSolutionBuilder(host, [configFile], { verbose: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild(configFile), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, configFile, "src/src/index.js"], - [Diagnostics.Building_project_0, `/${configFile}`] - ); - verifyOutputsPresent(fs, ["/src/src/index.js", "/src/src/index.d.ts"]); - host.clearDiagnostics(); - builder = createSolutionBuilder(host, [configFile], { verbose: true }); - tick(); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild(configFile), - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, configFile, "src/src/index.ts", "src/src/index.js"] - ); + verifyTscIncrementalEdits({ + scenario: "resolveJsonModule", + subScenario: "without outDir", + fs: () => projFs, + commandLineArgs: ["--b", "src/tsconfig_withFiles.json", "--verbose"], + modifyFs: fs => replaceText(fs, "src/tsconfig_withFiles.json", `"outDir": "dist",`, ""), + incrementalScenarios: [noChangeRun] }); }); @@ -125,32 +80,12 @@ export default hello.hello`); projFs = undefined!; // Release the contents }); - it("when importing json module from project reference", () => { - const expectedOutput = "/src/main/index.js"; - const { fs, tick } = getFsWithTime(projFs); - const configFile = "src/tsconfig.json"; - const stringsConfigFile = "src/strings/tsconfig.json"; - const mainConfigFile = "src/main/tsconfig.json"; - const host = fakes.SolutionBuilderHost.create(fs); - let builder = createSolutionBuilder(host, [configFile], { verbose: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild(stringsConfigFile, mainConfigFile, configFile), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, stringsConfigFile, "src/strings/tsconfig.tsbuildinfo"], - [Diagnostics.Building_project_0, `/${stringsConfigFile}`], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, mainConfigFile, "src/main/index.js"], - [Diagnostics.Building_project_0, `/${mainConfigFile}`], - ); - verifyOutputsPresent(fs, [expectedOutput]); - host.clearDiagnostics(); - builder = createSolutionBuilder(host, [configFile], { verbose: true }); - tick(); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild(stringsConfigFile, mainConfigFile, configFile), - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, stringsConfigFile, "src/strings/foo.json", "src/strings/tsconfig.tsbuildinfo"], - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, mainConfigFile, "src/main/index.ts", "src/main/index.js"], - ); + verifyTscIncrementalEdits({ + scenario: "resolveJsonModule", + subScenario: "importing json module from project reference", + fs: () => projFs, + commandLineArgs: ["--b", "src/tsconfig.json", "--verbose"], + incrementalScenarios: [noChangeRun] }); }); } diff --git a/src/testRunner/unittests/tsbuild/sample.ts b/src/testRunner/unittests/tsbuild/sample.ts index 1a27a624197..8d3602f1bb1 100644 --- a/src/testRunner/unittests/tsbuild/sample.ts +++ b/src/testRunner/unittests/tsbuild/sample.ts @@ -14,123 +14,63 @@ namespace ts { projFs = undefined!; // Release the contents }); + function getSampleFsAfterBuild() { + const fs = projFs.shadow(); + const host = fakes.SolutionBuilderHost.create(fs); + const builder = createSolutionBuilder(host, ["/src/tests"], {}); + builder.build(); + fs.makeReadonly(); + return fs; + } + describe("sanity check of clean build of 'sample1' project", () => { - it("can build the sample project 'sample1' without error", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: false }); - - host.clearDiagnostics(); - builder.build(); - host.assertDiagnosticMessages(/*empty*/); - - // Check for outputs. Not an exhaustive list - verifyOutputsPresent(fs, allExpectedOutputs); - }); - - it("builds correctly when outDir is specified", () => { - const fs = projFs.shadow(); - fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ + verifyTsc({ + scenario: "sample1", + subScenario: "builds correctly when outDir is specified", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tests"], + modifyFs: fs => fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ compilerOptions: { composite: true, declaration: true, sourceMap: true, outDir: "outDir" }, references: [{ path: "../core" }] - })); - - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/tests"], {}); - builder.build(); - host.assertDiagnosticMessages(/*empty*/); - const expectedOutputs = allExpectedOutputs.map(f => f.replace("/logic/", "/logic/outDir/")); - // Check for outputs. Not an exhaustive list - verifyOutputsPresent(fs, expectedOutputs); + })), }); - it("builds correctly when declarationDir is specified", () => { - const fs = projFs.shadow(); - fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ + verifyTsc({ + scenario: "sample1", + subScenario: "builds correctly when declarationDir is specified", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tests"], + modifyFs: fs => fs.writeFileSync("/src/logic/tsconfig.json", JSON.stringify({ compilerOptions: { composite: true, declaration: true, sourceMap: true, declarationDir: "out/decls" }, references: [{ path: "../core" }] - })); - - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/tests"], {}); - builder.build(); - host.assertDiagnosticMessages(/*empty*/); - const expectedOutputs = allExpectedOutputs.map(f => f.replace("/logic/index.d.ts", "/logic/out/decls/index.d.ts")); - // Check for outputs. Not an exhaustive list - verifyOutputsPresent(fs, expectedOutputs); + })), }); - it("builds correctly when project is not composite or doesnt have any references", () => { - const fs = projFs.shadow(); - replaceText(fs, "/src/core/tsconfig.json", `"composite": true,`, ""); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/core"], { verbose: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/core/tsconfig.json", "src/core/anotherModule.js"], - [Diagnostics.Building_project_0, "/src/core/tsconfig.json"] - ); - verifyOutputsPresent(fs, ["/src/core/index.js", "/src/core/index.d.ts", "/src/core/index.d.ts.map"]); + verifyTsc({ + scenario: "sample1", + subScenario: "builds correctly when project is not composite or doesnt have any references", + fs: () => projFs, + commandLineArgs: ["--b", "/src/core", "--verbose"], + modifyFs: fs => replaceText(fs, "/src/core/tsconfig.json", `"composite": true,`, ""), }); }); describe("dry builds", () => { - it("doesn't write any files in a dry build", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/tests"], { dry: true, force: false, verbose: false }); - builder.build(); - host.assertDiagnosticMessages( - [Diagnostics.A_non_dry_build_would_build_project_0, "/src/core/tsconfig.json"], - [Diagnostics.A_non_dry_build_would_build_project_0, "/src/logic/tsconfig.json"], - [Diagnostics.A_non_dry_build_would_build_project_0, "/src/tests/tsconfig.json"] - ); - - // Check for outputs to not be written. Not an exhaustive list - verifyOutputsAbsent(fs, allExpectedOutputs); - }); - - it("indicates that it would skip builds during a dry build", () => { - const { fs, tick } = getFsWithTime(projFs); - const host = fakes.SolutionBuilderHost.create(fs); - - let builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: false }); - builder.build(); - tick(); - - host.clearDiagnostics(); - builder = createSolutionBuilder(host, ["/src/tests"], { dry: true, force: false, verbose: false }); - builder.build(); - host.assertDiagnosticMessages( - [Diagnostics.Project_0_is_up_to_date, "/src/core/tsconfig.json"], - [Diagnostics.Project_0_is_up_to_date, "/src/logic/tsconfig.json"], - [Diagnostics.Project_0_is_up_to_date, "/src/tests/tsconfig.json"] - ); + verifyTsc({ + scenario: "sample1", + subScenario: "does not write any files in a dry build", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tests", "--dry"], }); }); describe("clean builds", () => { - it("removes all files it built", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - - const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: false }); - builder.build(); - // Verify they exist - verifyOutputsPresent(fs, allExpectedOutputs); - - builder.clean(); - // Verify they are gone - verifyOutputsAbsent(fs, allExpectedOutputs); - - // Subsequent clean shouldn't throw / etc - builder.clean(); - verifyOutputsAbsent(fs, allExpectedOutputs); - - builder.build(); - // Verify they exist - verifyOutputsPresent(fs, allExpectedOutputs); + verifyTscIncrementalEdits({ + scenario: "sample1", + subScenario: "removes all files it built", + fs: getSampleFsAfterBuild, + commandLineArgs: ["--b", "/src/tests", "--clean"], + incrementalScenarios: [noChangeRun] }); it("cleans till project specified", () => { @@ -158,29 +98,12 @@ namespace ts { }); describe("force builds", () => { - it("always builds under --force", () => { - const { fs, time, tick } = getFsWithTime(projFs); - const host = fakes.SolutionBuilderHost.create(fs); - - let builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: true, verbose: false }); - builder.build(); - let currentTime = time(); - checkOutputTimestamps(currentTime); - - tick(); - Debug.assert(time() !== currentTime, "Time moves on"); - currentTime = time(); - builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: true, verbose: false }); - builder.build(); - checkOutputTimestamps(currentTime); - - function checkOutputTimestamps(expected: number) { - // Check timestamps - for (const output of allExpectedOutputs) { - const actual = fs.statSync(output).mtimeMs; - assert(actual === expected, `File ${output} has timestamp ${actual}, expected ${expected}`); - } - } + verifyTscIncrementalEdits({ + scenario: "sample1", + subScenario: "always builds under with force option", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tests", "--force"], + incrementalScenarios: [noChangeRun] }); }); @@ -196,64 +119,42 @@ namespace ts { return { fs, host, builder }; } - it("Builds the project", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/tests"], { verbose: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/core/tsconfig.json", "src/core/anotherModule.js"], - [Diagnostics.Building_project_0, "/src/core/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/logic/tsconfig.json", "src/logic/index.js"], - [Diagnostics.Building_project_0, "/src/logic/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/tests/tsconfig.json", "src/tests/index.js"], - [Diagnostics.Building_project_0, "/src/tests/tsconfig.json"] - ); - }); - - // All three projects are up to date - it("Detects that all projects are up to date", () => { - const { host, builder } = initializeWithBuild(); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"), - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/core/tsconfig.json", "src/core/anotherModule.ts", "src/core/anotherModule.js"], - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/logic/tsconfig.json", "src/logic/index.ts", "src/logic/index.js"], - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/tests/tsconfig.json", "src/tests/index.ts", "src/tests/index.js"] - ); - }); - - // Update a file in the leaf node (tests), only it should rebuild the last one - it("Only builds the leaf node project", () => { - const { fs, host, builder } = initializeWithBuild(); - fs.writeFileSync("/src/tests/index.ts", "const m = 10;"); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"), - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/core/tsconfig.json", "src/core/anotherModule.ts", "src/core/anotherModule.js"], - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/logic/tsconfig.json", "src/logic/index.ts", "src/logic/index.js"], - [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, "src/tests/tsconfig.json", "src/tests/index.js", "src/tests/index.ts"], - [Diagnostics.Building_project_0, "/src/tests/tsconfig.json"] - ); - }); - - // Update a file in the parent (without affecting types), should get fast downstream builds - it("Detects type-only changes in upstream projects", () => { - const { fs, host, builder } = initializeWithBuild(); - replaceText(fs, "/src/core/index.ts", "HELLO WORLD", "WELCOME PLANET"); - builder.build(); - - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, "src/core/tsconfig.json", "src/core/anotherModule.js", "src/core/index.ts"], - [Diagnostics.Building_project_0, "/src/core/tsconfig.json"], - [Diagnostics.Updating_unchanged_output_timestamps_of_project_0, "/src/core/tsconfig.json"], - [Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, "src/logic/tsconfig.json"], - [Diagnostics.Updating_output_timestamps_of_project_0, "/src/logic/tsconfig.json"], - [Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, "src/tests/tsconfig.json"], - [Diagnostics.Updating_output_timestamps_of_project_0, "/src/tests/tsconfig.json"] - ); + verifyTscIncrementalEdits({ + scenario: "sample1", + subScenario: "can detect when and what to rebuild", + fs: getSampleFsAfterBuild, + commandLineArgs: ["--b", "/src/tests", "--verbose"], + incrementalScenarios: [ + // Update a file in the leaf node (tests), only it should rebuild the last one + { + subScenario: "Only builds the leaf node project", + buildKind: BuildKind.IncrementalDtsUnchanged, + modifyFs: fs => fs.writeFileSync("/src/tests/index.ts", "const m = 10;"), + }, + // Update a file in the parent (without affecting types), should get fast downstream builds + { + subScenario: "Detects type-only changes in upstream projects", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => replaceText(fs, "/src/core/index.ts", "HELLO WORLD", "WELCOME PLANET"), + }, + { + subScenario: "indicates that it would skip builds during a dry build", + buildKind: BuildKind.IncrementalDtsUnchanged, + modifyFs: noop, + commandLineArgs: ["--b", "/src/tests", "--dry"], + }, + { + subScenario: "rebuilds from start if force option is set", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: noop, + commandLineArgs: ["--b", "/src/tests", "--verbose", "--force"], + }, + { + subScenario: "rebuilds when tsconfig changes", + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => replaceText(fs, "/src/tests/tsconfig.json", `"composite": true`, `"composite": true, "target": "es3"`), + }, + ] }); it("rebuilds completely when version in tsbuildinfo doesnt match ts version", () => { @@ -300,61 +201,19 @@ namespace ts { ); }); - it("rebuilds from start if --f is passed", () => { - const { host, builder } = initializeWithBuild({ force: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"), - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/core/tsconfig.json", "src/core/anotherModule.ts", "src/core/anotherModule.js"], - [Diagnostics.Building_project_0, "/src/core/tsconfig.json"], - [Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, "src/logic/tsconfig.json"], - [Diagnostics.Building_project_0, "/src/logic/tsconfig.json"], - [Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, "src/tests/tsconfig.json"], - [Diagnostics.Building_project_0, "/src/tests/tsconfig.json"] - ); - }); - - it("rebuilds when tsconfig changes", () => { - const { fs, host, builder } = initializeWithBuild(); - replaceText(fs, "/src/tests/tsconfig.json", `"composite": true`, `"composite": true, "target": "es3"`); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"), - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/core/tsconfig.json", "src/core/anotherModule.ts", "src/core/anotherModule.js"], - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/logic/tsconfig.json", "src/logic/index.ts", "src/logic/index.js"], - [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, "src/tests/tsconfig.json", "src/tests/index.js", "src/tests/tsconfig.json"], - [Diagnostics.Building_project_0, "/src/tests/tsconfig.json"], - ); - }); - - it("rebuilds when extended config file changes", () => { - const { fs, tick } = getFsWithTime(projFs); - fs.writeFileSync("/src/tests/tsconfig.base.json", JSON.stringify({ compilerOptions: { target: "es3" } })); - replaceText(fs, "/src/tests/tsconfig.json", `"references": [`, `"extends": "./tsconfig.base.json", "references": [`); - const host = fakes.SolutionBuilderHost.create(fs); - let builder = createSolutionBuilder(host, ["/src/tests"], { verbose: true }); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/core/tsconfig.json", "src/core/anotherModule.js"], - [Diagnostics.Building_project_0, "/src/core/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/logic/tsconfig.json", "src/logic/index.js"], - [Diagnostics.Building_project_0, "/src/logic/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/tests/tsconfig.json", "src/tests/index.js"], - [Diagnostics.Building_project_0, "/src/tests/tsconfig.json"] - ); - host.clearDiagnostics(); - tick(); - builder = createSolutionBuilder(host, ["/src/tests"], { verbose: true }); - fs.writeFileSync("/src/tests/tsconfig.base.json", JSON.stringify({ compilerOptions: {} })); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"), - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/core/tsconfig.json", "src/core/anotherModule.ts", "src/core/anotherModule.js"], - [Diagnostics.Project_0_is_up_to_date_because_newest_input_1_is_older_than_oldest_output_2, "src/logic/tsconfig.json", "src/logic/index.ts", "src/logic/index.js"], - [Diagnostics.Project_0_is_out_of_date_because_oldest_output_1_is_older_than_newest_input_2, "src/tests/tsconfig.json", "src/tests/index.js", "src/tests/tsconfig.base.json"], - [Diagnostics.Building_project_0, "/src/tests/tsconfig.json"] - ); + verifyTscIncrementalEdits({ + scenario: "sample1", + subScenario: "rebuilds when extended config file changes", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tests", "--verbose"], + modifyFs: fs => { + fs.writeFileSync("/src/tests/tsconfig.base.json", JSON.stringify({ compilerOptions: { target: "es3" } })); + replaceText(fs, "/src/tests/tsconfig.json", `"references": [`, `"extends": "./tsconfig.base.json", "references": [`); + }, + incrementalScenarios: [{ + buildKind: BuildKind.IncrementalDtsChange, + modifyFs: fs => fs.writeFileSync("/src/tests/tsconfig.base.json", JSON.stringify({ compilerOptions: {} })) + }] }); it("builds till project specified", () => { @@ -435,27 +294,12 @@ namespace ts { }); describe("downstream-blocked compilations", () => { - it("won't build downstream projects if upstream projects have errors", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/tests"], { dry: false, force: false, verbose: true }); - - // Induce an error in the middle project - replaceText(fs, "/src/logic/index.ts", "c.multiply(10, 15)", `c.muitply()`); - builder.build(); - host.assertDiagnosticMessages( - getExpectedDiagnosticForProjectsInBuild("src/core/tsconfig.json", "src/logic/tsconfig.json", "src/tests/tsconfig.json"), - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/core/tsconfig.json", "src/core/anotherModule.js"], - [Diagnostics.Building_project_0, "/src/core/tsconfig.json"], - [Diagnostics.Project_0_is_out_of_date_because_output_file_1_does_not_exist, "src/logic/tsconfig.json", "src/logic/index.js"], - [Diagnostics.Building_project_0, "/src/logic/tsconfig.json"], - { - message: [Diagnostics.Property_0_does_not_exist_on_type_1, "muitply", `typeof import("/src/core/index")`], - location: expectedLocationIndexOf(fs, "/src/logic/index.ts", "muitply"), - }, - [Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, "src/tests/tsconfig.json", "src/logic"], - [Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, "/src/tests/tsconfig.json", "/src/logic"] - ); + verifyTsc({ + scenario: "sample1", + subScenario: "does not build downstream projects if upstream projects have errors", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tests", "--verbose"], + modifyFs: fs => replaceText(fs, "/src/logic/index.ts", "c.multiply(10, 15)", `c.muitply()`) }); }); @@ -515,54 +359,17 @@ export class cNew {}`); }); describe("lists files", () => { - it("listFiles", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/tests"], { listFiles: true }); - builder.build(); - assert.deepEqual(host.traces, [ - "/lib/lib.d.ts", - "/src/core/anotherModule.ts", - "/src/core/index.ts", - "/src/core/some_decl.d.ts", - "/lib/lib.d.ts", - ...getCoreOutputs(), - "/src/logic/index.ts", - "/lib/lib.d.ts", - ...getCoreOutputs(), - "/src/logic/index.d.ts", - "/src/tests/index.ts" - ]); - - function getCoreOutputs() { - return [ - "/src/core/index.d.ts", - "/src/core/anotherModule.d.ts" - ]; - } + verifyTsc({ + scenario: "sample1", + subScenario: "listFiles", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tests", "--listFiles"], }); - - it("listEmittedFiles", () => { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - const builder = createSolutionBuilder(host, ["/src/tests"], { listEmittedFiles: true }); - builder.build(); - assert.deepEqual(host.traces, [ - "TSFILE: /src/core/anotherModule.js", - "TSFILE: /src/core/anotherModule.d.ts.map", - "TSFILE: /src/core/anotherModule.d.ts", - "TSFILE: /src/core/index.js", - "TSFILE: /src/core/index.d.ts.map", - "TSFILE: /src/core/index.d.ts", - "TSFILE: /src/core/tsconfig.tsbuildinfo", - "TSFILE: /src/logic/index.js.map", - "TSFILE: /src/logic/index.js", - "TSFILE: /src/logic/index.d.ts", - "TSFILE: /src/logic/tsconfig.tsbuildinfo", - "TSFILE: /src/tests/index.js", - "TSFILE: /src/tests/index.d.ts", - "TSFILE: /src/tests/tsconfig.tsbuildinfo", - ]); + verifyTsc({ + scenario: "sample1", + subScenario: "listEmittedFiles", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tests", "--listEmittedFiles"], }); }); @@ -590,7 +397,8 @@ class someClass { }`), buildKind: BuildKind.IncrementalDtsChange, modifyFs: fs => replaceText(fs, "/src/logic/tsconfig.json", `"declaration": true,`, `"declaration": true, "declarationDir": "decls",`), - } + }, + noChangeRun, ], }); diff --git a/src/testRunner/unittests/tsbuild/transitiveReferences.ts b/src/testRunner/unittests/tsbuild/transitiveReferences.ts index 99fcd75d087..735c13f5976 100644 --- a/src/testRunner/unittests/tsbuild/transitiveReferences.ts +++ b/src/testRunner/unittests/tsbuild/transitiveReferences.ts @@ -1,23 +1,6 @@ namespace ts { describe("unittests:: tsbuild:: when project reference is referenced transitively", () => { let projFs: vfs.FileSystem; - const allExpectedOutputs = [ - "/src/a.js", "/src/a.d.ts", - "/src/b.js", "/src/b.d.ts", - "/src/c.js" - ]; - const expectedFileTraces = [ - "/lib/lib.d.ts", - "/src/a.ts", - "/lib/lib.d.ts", - "/src/a.d.ts", - "/src/b.ts", - "/lib/lib.d.ts", - "/src/a.d.ts", - "/src/b.d.ts", - "/src/refs/a.d.ts", - "/src/c.ts" - ]; before(() => { projFs = loadProjectFromDisk("tests/projects/transitiveReferences"); }); @@ -25,17 +8,6 @@ namespace ts { projFs = undefined!; // Release the contents }); - function verifyBuild(modifyDiskLayout: (fs: vfs.FileSystem) => void, allExpectedOutputs: readonly string[], expectedFileTraces: readonly string[], ...expectedDiagnostics: fakes.ExpectedDiagnostic[]) { - const fs = projFs.shadow(); - const host = fakes.SolutionBuilderHost.create(fs); - modifyDiskLayout(fs); - const builder = createSolutionBuilder(host, ["/src/tsconfig.c.json"], { listFiles: true }); - builder.build(); - host.assertDiagnosticMessages(...expectedDiagnostics); - verifyOutputsPresent(fs, allExpectedOutputs); - assert.deepEqual(host.traces, expectedFileTraces); - } - function modifyFsBTsToNonRelativeImport(fs: vfs.FileSystem, moduleResolution: "node" | "classic") { fs.writeFileSync("/src/b.ts", `import {A} from 'a'; export const b = new A();`); @@ -49,35 +21,27 @@ export const b = new A();`); })); } - it("verify that it builds correctly", () => { - verifyBuild(noop, allExpectedOutputs, expectedFileTraces); + verifyTsc({ + scenario: "transitiveReferences", + subScenario: "builds correctly", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig.c.json", "--listFiles"], }); - it("verify that it builds correctly when the referenced project uses different module resolution", () => { - verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "classic"), allExpectedOutputs, expectedFileTraces); + verifyTsc({ + scenario: "transitiveReferences", + subScenario: "builds correctly when the referenced project uses different module resolution", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig.c.json", "--listFiles"], + modifyFs: fs => modifyFsBTsToNonRelativeImport(fs, "classic"), }); - it("verify that it build reports error about module not found with node resolution with external module name", () => { - // Error in b build only a - const allExpectedOutputs = ["/src/a.js", "/src/a.d.ts"]; - const expectedFileTraces = [ - "/lib/lib.d.ts", - "/src/a.ts", - "/lib/lib.d.ts", - "/src/b.ts" - ]; - verifyBuild(fs => modifyFsBTsToNonRelativeImport(fs, "node"), - allExpectedOutputs, - expectedFileTraces, - { - message: [Diagnostics.Cannot_find_module_0, "a"], - location: { - file: "/src/b.ts", - start: `import {A} from 'a';`.indexOf(`'a'`), - length: `'a'`.length - } - }, - ); + verifyTsc({ + scenario: "transitiveReferences", + subScenario: "reports error about module not found with node resolution with external module name", + fs: () => projFs, + commandLineArgs: ["--b", "/src/tsconfig.c.json", "--listFiles"], + modifyFs: fs => modifyFsBTsToNonRelativeImport(fs, "node"), }); }); } diff --git a/src/testRunner/unittests/tsc/helpers.ts b/src/testRunner/unittests/tsc/helpers.ts index ad1d64ac285..ed3ac65cc96 100644 --- a/src/testRunner/unittests/tsc/helpers.ts +++ b/src/testRunner/unittests/tsc/helpers.ts @@ -3,158 +3,20 @@ namespace ts { writtenFiles: Map; baseLine(): void; }; - function executeCommandLine(sys: TscCompileSystem, commandLineArgs: readonly string[]) { - if (isBuild(commandLineArgs)) { - return performBuild(sys, commandLineArgs.slice(1)); - } - - const reportDiagnostic = createDiagnosticReporter(sys); - const commandLine = parseCommandLine(commandLineArgs, path => sys.readFile(path)); - if (commandLine.options.build) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_build_must_be_the_first_command_line_argument)); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - - if (commandLine.errors.length > 0) { - commandLine.errors.forEach(reportDiagnostic); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - - let configFileName: string | undefined; - if (commandLine.options.project) { - if (commandLine.fileNames.length !== 0) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line)); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - - const fileOrDirectory = normalizePath(commandLine.options.project); - if (!fileOrDirectory /* current directory "." */ || sys.directoryExists(fileOrDirectory)) { - configFileName = combinePaths(fileOrDirectory, "tsconfig.json"); - if (!sys.fileExists(configFileName)) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project)); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - } - else { - configFileName = fileOrDirectory; - if (!sys.fileExists(configFileName)) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project)); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - } - } - else if (commandLine.fileNames.length === 0) { - const searchPath = normalizePath(sys.getCurrentDirectory()); - configFileName = findConfigFile(searchPath, sys.fileExists); - } - - Debug.assert(commandLine.fileNames.length !== 0 || !!configFileName); - - if (configFileName) { - const configParseResult = Debug.assertDefined(parseConfigFileWithSystem(configFileName, commandLine.options, sys, reportDiagnostic)); - if (isIncrementalCompilation(configParseResult.options)) { - performIncrementalCompilation(sys, configParseResult); - } - else { - performCompilation(sys, configParseResult); - } - } - else { - if (isIncrementalCompilation(commandLine.options)) { - performIncrementalCompilation(sys, commandLine); - } - else { - performCompilation(sys, commandLine); - } - } - } - - function createReportErrorSummary(sys: TscCompileSystem, options: CompilerOptions): ReportEmitErrorSummary | undefined { - return options.pretty ? - errorCount => sys.write(getErrorSummaryText(errorCount, sys.newLine)) : - undefined; - } - - function performCompilation(sys: TscCompileSystem, config: ParsedCommandLine) { - const { fileNames, options, projectReferences } = config; - const reportDiagnostic = createDiagnosticReporter(sys, options.pretty); - const host = createCompilerHostWorker(options, /*setParentPos*/ undefined, sys); - const currentDirectory = host.getCurrentDirectory(); - const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - changeCompilerHostLikeToUseCache(host, fileName => toPath(fileName, currentDirectory, getCanonicalFileName)); - const program = createProgram({ - rootNames: fileNames, - options, - projectReferences, - host, - configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config) - }); - const exitStatus = emitFilesAndReportErrorsAndGetExitStatus( - program, - reportDiagnostic, - s => sys.write(s + sys.newLine), - createReportErrorSummary(sys, options) - ); - baselineBuildInfo([config], sys.vfs, sys.writtenFiles); - return sys.exit(exitStatus); - } - - function performIncrementalCompilation(sys: TscCompileSystem, config: ParsedCommandLine) { - const reportDiagnostic = createDiagnosticReporter(sys, config.options.pretty); - const { options, fileNames, projectReferences } = config; - const exitCode = ts.performIncrementalCompilation({ - system: sys, - rootNames: fileNames, - options, - configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config), - projectReferences, - reportDiagnostic, - reportErrorSummary: createReportErrorSummary(sys, options), - }); - baselineBuildInfo([config], sys.vfs, sys.writtenFiles); - return sys.exit(exitCode); - } - - function performBuild(sys: TscCompileSystem, args: string[]) { - const { buildOptions, projects, errors } = parseBuildCommand(args); - const reportDiagnostic = createDiagnosticReporter(sys, buildOptions.pretty); - - if (errors.length > 0) { - errors.forEach(reportDiagnostic); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - - Debug.assert(projects.length !== 0); - - const buildHost = createSolutionBuilderHost( - sys, - /*createProgram*/ undefined, - reportDiagnostic, - createBuilderStatusReporter(sys, buildOptions.pretty), - createReportErrorSummary(sys, buildOptions) - ); - fakes.patchSolutionBuilderHost(buildHost, sys); - const builder = createSolutionBuilder(buildHost, projects, buildOptions); - const exitCode = buildOptions.clean ? builder.clean() : builder.build(); - baselineBuildInfo(builder.getAllParsedConfigs(), sys.vfs, sys.writtenFiles); - return sys.exit(exitCode); - } - - function isBuild(commandLineArgs: readonly string[]) { - if (commandLineArgs.length > 0 && commandLineArgs[0].charCodeAt(0) === CharacterCodes.minus) { - const firstOption = commandLineArgs[0].slice(commandLineArgs[0].charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase(); - return firstOption === "build" || firstOption === "b"; - } - return false; - } export enum BuildKind { Initial = "initial-build", IncrementalDtsChange = "incremental-declaration-changes", IncrementalDtsUnchanged = "incremental-declaration-doesnt-change", - IncrementalHeadersChange = "incremental-headers-change-without-dts-changes" + IncrementalHeadersChange = "incremental-headers-change-without-dts-changes", + NoChangeRun ="no-change-run" } + export const noChangeRun: TscIncremental = { + buildKind: BuildKind.NoChangeRun, + modifyFs: noop + }; + export interface TscCompile { scenario: string; subScenario: string; @@ -198,8 +60,17 @@ namespace ts { sys.write(`${sys.getExecutingFilePath()} ${commandLineArgs.join(" ")}\n`); sys.exit = exitCode => sys.exitCode = exitCode; - executeCommandLine(sys, commandLineArgs); - sys.write(`exitCode:: ${sys.exitCode}\n`); + executeCommandLine( + sys, + { + onCompilerHostCreate: host => fakes.patchHostForBuildInfoReadWrite(host), + onCompilationComplete: config => baselineBuildInfo([config], sys.vfs, sys.writtenFiles), + onSolutionBuilderHostCreate: host => fakes.patchSolutionBuilderHost(host, sys), + onSolutionBuildComplete: configs => baselineBuildInfo(configs, sys.vfs, sys.writtenFiles), + }, + commandLineArgs, + ); + sys.write(`exitCode:: ExitStatus.${ExitStatus[sys.exitCode as ExitStatus]}\n`); if (baselineReadFileCalls) { sys.write(`readFiles:: ${JSON.stringify(actualReadFileMap, /*replacer*/ undefined, " ")} `); } diff --git a/src/testRunner/unittests/tsc/incremental.ts b/src/testRunner/unittests/tsc/incremental.ts new file mode 100644 index 00000000000..17cc7f49bdc --- /dev/null +++ b/src/testRunner/unittests/tsc/incremental.ts @@ -0,0 +1,76 @@ +namespace ts { + describe("unittests:: tsc:: incremental::", () => { + verifyTscIncrementalEdits({ + scenario: "incremental", + subScenario: "when passing filename for buildinfo on commandline", + fs: () => loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": utils.dedent` + { + "compilerOptions": { + "target": "es5", + "module": "commonjs", + }, + "include": [ + "src/**/*.ts" + ] + }`, + }), + commandLineArgs: ["--incremental", "--p", "src/project", "--tsBuildInfoFile", "src/project/.tsbuildinfo"], + incrementalScenarios: [noChangeRun] + }); + + verifyTscIncrementalEdits({ + scenario: "incremental", + subScenario: "when passing rootDir from commandline", + fs: () => loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": utils.dedent` + { + "compilerOptions": { + "incremental": true, + "outDir": "dist", + }, + }`, + }), + commandLineArgs: ["--p", "src/project", "--rootDir", "src/project/src"], + incrementalScenarios: [noChangeRun] + }); + + verifyTscIncrementalEdits({ + scenario: "incremental", + subScenario: "with only dts files", + fs: () => loadProjectFromFiles({ + "/src/project/src/main.d.ts": "export const x = 10;", + "/src/project/src/another.d.ts": "export const y = 10;", + "/src/project/tsconfig.json": "{}", + }), + commandLineArgs: ["--incremental", "--p", "src/project"], + incrementalScenarios: [ + noChangeRun, + { + buildKind: BuildKind.IncrementalDtsUnchanged, + modifyFs: fs => appendText(fs, "/src/project/src/main.d.ts", "export const xy = 100;") + } + ] + }); + + verifyTscIncrementalEdits({ + scenario: "incremental", + subScenario: "when passing rootDir is in the tsconfig", + fs: () => loadProjectFromFiles({ + "/src/project/src/main.ts": "export const x = 10;", + "/src/project/tsconfig.json": utils.dedent` + { + "compilerOptions": { + "incremental": true, + "outDir": "./built", + "rootDir": "./" + }, + }`, + }), + commandLineArgs: ["--p", "src/project"], + incrementalScenarios: [noChangeRun] + }); + }); +} diff --git a/src/testRunner/unittests/tsc/listFilesOnly.ts b/src/testRunner/unittests/tsc/listFilesOnly.ts new file mode 100644 index 00000000000..5655d3d7614 --- /dev/null +++ b/src/testRunner/unittests/tsc/listFilesOnly.ts @@ -0,0 +1,23 @@ +namespace ts { + describe("unittests:: tsc:: listFilesOnly::", () => { + verifyTsc({ + scenario: "listFilesOnly", + subScenario: "combined with watch", + fs: () => loadProjectFromFiles({ + "/src/test.ts": utils.dedent` + export const x = 1;`, + }), + commandLineArgs: ["/src/test.ts", "--watch", "--listFilesOnly"] + }); + + verifyTsc({ + scenario: "listFilesOnly", + subScenario: "loose file", + fs: () => loadProjectFromFiles({ + "/src/test.ts": utils.dedent` + export const x = 1;`, + }), + commandLineArgs: ["/src/test.ts", "--listFilesOnly"] + }); + }); +} diff --git a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts index 908c609e703..0de8e8e1948 100644 --- a/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts +++ b/src/testRunner/unittests/tscWatch/emitAndErrorUpdates.ts @@ -1,8 +1,7 @@ namespace ts.tscWatch { describe("unittests:: tsc-watch:: Emit times and Error updates in builder after program changes", () => { - const currentDirectory = "/user/username/projects/myproject"; const config: File = { - path: `${currentDirectory}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: `{}` }; function getOutputFileStampAndError(host: WatchedSystem, watch: Watch, file: File) { @@ -83,7 +82,7 @@ namespace ts.tscWatch { const nonLibFiles = [...filesWithNewEmit, ...filesWithOnlyErrorRefresh, ...filesNotTouched]; const files = [...nonLibFiles, configFile, libFile]; const compilerOptions = (JSON.parse(configFile.content).compilerOptions || {}) as CompilerOptions; - const host = createWatchedSystem(files, { currentDirectory }); + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); const watch = createWatchOfConfigFile("tsconfig.json", host); checkProgramActualFiles(watch(), [...nonLibFiles.map(f => f.path), libFile.path]); checkOutputErrorsInitial(host, getInitialErrors(watch)); @@ -167,7 +166,7 @@ namespace ts.tscWatch { describe("deep import changes", () => { const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `import {B} from './b'; declare var console: any; let b = new B(); @@ -203,7 +202,7 @@ console.log(b.c.d);` describe("updates errors when deep import file changes", () => { const bFile: File = { - path: `${currentDirectory}/b.ts`, + path: `${projectRoot}/b.ts`, content: `import {C} from './c'; export class B { @@ -211,7 +210,7 @@ export class B }` }; const cFile: File = { - path: `${currentDirectory}/c.ts`, + path: `${projectRoot}/c.ts`, content: `export class C { d = 1; @@ -222,7 +221,7 @@ export class B describe("updates errors when deep import through declaration file changes", () => { const bFile: File = { - path: `${currentDirectory}/b.d.ts`, + path: `${projectRoot}/b.d.ts`, content: `import {C} from './c'; export class B { @@ -230,7 +229,7 @@ export class B }` }; const cFile: File = { - path: `${currentDirectory}/c.d.ts`, + path: `${projectRoot}/c.d.ts`, content: `export class C { d: number; @@ -242,7 +241,7 @@ export class B describe("updates errors in file not exporting a deep multilevel import that changes", () => { const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `export interface Point { name: string; c: Coords; @@ -253,13 +252,13 @@ export interface Coords { }` }; const bFile: File = { - path: `${currentDirectory}/b.ts`, + path: `${projectRoot}/b.ts`, content: `import { Point } from "./a"; export interface PointWrapper extends Point { }` }; const cFile: File = { - path: `${currentDirectory}/c.ts`, + path: `${projectRoot}/c.ts`, content: `import { PointWrapper } from "./b"; export function getPoint(): PointWrapper { return { @@ -272,12 +271,12 @@ export function getPoint(): PointWrapper { };` }; const dFile: File = { - path: `${currentDirectory}/d.ts`, + path: `${projectRoot}/d.ts`, content: `import { getPoint } from "./c"; getPoint().c.x;` }; const eFile: File = { - path: `${currentDirectory}/e.ts`, + path: `${projectRoot}/e.ts`, content: `import "./d";` }; verifyEmitAndErrorUpdates({ @@ -301,14 +300,14 @@ getPoint().c.x;` describe("updates errors when file transitively exported file changes", () => { const config: File = { - path: `${currentDirectory}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: JSON.stringify({ files: ["app.ts"], compilerOptions: { baseUrl: "." } }) }; const app: File = { - path: `${currentDirectory}/app.ts`, + path: `${projectRoot}/app.ts`, content: `import { Data } from "lib2/public"; export class App { public constructor() { @@ -317,11 +316,11 @@ export class App { }` }; const lib2Public: File = { - path: `${currentDirectory}/lib2/public.ts`, + path: `${projectRoot}/lib2/public.ts`, content: `export * from "./data";` }; const lib2Data: File = { - path: `${currentDirectory}/lib2/data.ts`, + path: `${projectRoot}/lib2/data.ts`, content: `import { ITest } from "lib1/public"; export class Data { public test() { @@ -333,15 +332,15 @@ export class Data { }` }; const lib1Public: File = { - path: `${currentDirectory}/lib1/public.ts`, + path: `${projectRoot}/lib1/public.ts`, content: `export * from "./tools/public";` }; const lib1ToolsPublic: File = { - path: `${currentDirectory}/lib1/tools/public.ts`, + path: `${projectRoot}/lib1/tools/public.ts`, content: `export * from "./tools.interface";` }; const lib1ToolsInterface: File = { - path: `${currentDirectory}/lib1/tools/tools.interface.ts`, + path: `${projectRoot}/lib1/tools/tools.interface.ts`, content: `export interface ITest { title: string; }` @@ -372,7 +371,7 @@ export class Data { describe("when there are circular import and exports", () => { const lib2Data: File = { - path: `${currentDirectory}/lib2/data.ts`, + path: `${projectRoot}/lib2/data.ts`, content: `import { ITest } from "lib1/public"; import { Data2 } from "./data2"; export class Data { public dat?: Data2; public test() { @@ -384,7 +383,7 @@ export class Data { }` }; const lib2Data2: File = { - path: `${currentDirectory}/lib2/data2.ts`, + path: `${projectRoot}/lib2/data2.ts`, content: `import { Data } from "./data"; export class Data2 { public dat?: Data; diff --git a/src/testRunner/unittests/tscWatch/helpers.ts b/src/testRunner/unittests/tscWatch/helpers.ts index a58785dc7db..1ab49cec139 100644 --- a/src/testRunner/unittests/tscWatch/helpers.ts +++ b/src/testRunner/unittests/tscWatch/helpers.ts @@ -1,3 +1,7 @@ +namespace ts { + export const projects = `/user/username/projects`; + export const projectRoot = `${projects}/myproject`; +} namespace ts.tscWatch { export import WatchedSystem = TestFSWithWatch.TestServerHost; export type File = TestFSWithWatch.File; diff --git a/src/testRunner/unittests/tscWatch/programUpdates.ts b/src/testRunner/unittests/tscWatch/programUpdates.ts index ed2a15c9a14..0b9cc883b85 100644 --- a/src/testRunner/unittests/tscWatch/programUpdates.ts +++ b/src/testRunner/unittests/tscWatch/programUpdates.ts @@ -918,20 +918,19 @@ namespace ts.tscWatch { describe("should not trigger should not trigger recompilation because of program emit", () => { function verifyWithOptions(options: CompilerOptions, outputFiles: readonly string[]) { - const proj = "/user/username/projects/myproject"; const file1: File = { - path: `${proj}/file1.ts`, + path: `${projectRoot}/file1.ts`, content: "export const c = 30;" }; const file2: File = { - path: `${proj}/src/file2.ts`, + path: `${projectRoot}/src/file2.ts`, content: `import {c} from "file1"; export const d = 30;` }; const tsconfig: File = { - path: `${proj}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: generateTSConfig(options, emptyArray, "\n") }; - const host = createWatchedSystem([file1, file2, libFile, tsconfig], { currentDirectory: proj }); + const host = createWatchedSystem([file1, file2, libFile, tsconfig], { currentDirectory: projectRoot }); const watch = createWatchOfConfigFile(tsconfig.path, host, /*optionsToExtend*/ undefined, /*maxNumberOfFilesToIterateForInvalidation*/1); checkProgramActualFiles(watch(), [file1.path, file2.path, libFile.path]); @@ -1020,9 +1019,8 @@ namespace ts.tscWatch { }); it("updates errors correctly when declaration emit is disabled in compiler options", () => { - const currentDirectory = "/user/username/projects/myproject"; const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `import test from './b'; test(4, 5);` }; @@ -1031,11 +1029,11 @@ test(4, 5);` } export default test;`; const bFile: File = { - path: `${currentDirectory}/b.ts`, + path: `${projectRoot}/b.ts`, content: bFileContent }; const tsconfigFile: File = { - path: `${currentDirectory}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { module: "commonjs", @@ -1045,7 +1043,7 @@ export default test;`; }) }; const files = [aFile, bFile, libFile, tsconfigFile]; - const host = createWatchedSystem(files, { currentDirectory }); + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); const watch = createWatchOfConfigFile("tsconfig.json", host); checkOutputErrorsInitial(host, emptyArray); @@ -1072,22 +1070,21 @@ export default test;`; }); it("updates errors when strictNullChecks changes", () => { - const currentDirectory = "/user/username/projects/myproject"; const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `declare function foo(): null | { hello: any }; foo().hello` }; const config: File = { - path: `${currentDirectory}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: JSON.stringify({ compilerOptions: {} }) }; const files = [aFile, config, libFile]; - const host = createWatchedSystem(files, { currentDirectory }); + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); const watch = createWatchOfConfigFile("tsconfig.json", host); checkProgramActualFiles(watch(), [aFile.path, libFile.path]); checkOutputErrorsInitial(host, emptyArray); - const modifiedTimeOfAJs = host.getModifiedTime(`${currentDirectory}/a.js`); + const modifiedTimeOfAJs = host.getModifiedTime(`${projectRoot}/a.js`); host.writeFile(config.path, JSON.stringify({ compilerOptions: { strictNullChecks: true } })); host.runQueuedTimeoutCallbacks(); const expectedStrictNullErrors = [ @@ -1095,39 +1092,38 @@ foo().hello` ]; checkOutputErrorsIncremental(host, expectedStrictNullErrors); // File a need not be rewritten - assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); + assert.equal(host.getModifiedTime(`${projectRoot}/a.js`), modifiedTimeOfAJs); host.writeFile(config.path, JSON.stringify({ compilerOptions: { strict: true, alwaysStrict: false } })); // Avoid changing 'alwaysStrict' or must re-bind host.runQueuedTimeoutCallbacks(); checkOutputErrorsIncremental(host, expectedStrictNullErrors); // File a need not be rewritten - assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); + assert.equal(host.getModifiedTime(`${projectRoot}/a.js`), modifiedTimeOfAJs); host.writeFile(config.path, JSON.stringify({ compilerOptions: {} })); host.runQueuedTimeoutCallbacks(); checkOutputErrorsIncremental(host, emptyArray); // File a need not be rewritten - assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs); + assert.equal(host.getModifiedTime(`${projectRoot}/a.js`), modifiedTimeOfAJs); }); it("updates errors when ambient modules of program changes", () => { - const currentDirectory = "/user/username/projects/myproject"; const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `declare module 'a' { type foo = number; }` }; const config: File = { - path: `${currentDirectory}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: "{}" }; const files = [aFile, config, libFile]; - const host = createWatchedSystem(files, { currentDirectory }); + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); const watch = createWatchOfConfigFile("tsconfig.json", host); checkProgramActualFiles(watch(), [aFile.path, libFile.path]); checkOutputErrorsInitial(host, emptyArray); // Create bts with same file contents - const bTsPath = `${currentDirectory}/b.ts`; + const bTsPath = `${projectRoot}/b.ts`; host.writeFile(bTsPath, aFile.content); host.runQueuedTimeoutCallbacks(); checkProgramActualFiles(watch(), [aFile.path, "b.ts", libFile.path]); @@ -1144,7 +1140,6 @@ foo().hello` }); describe("updates errors in lib file", () => { - const currentDirectory = "/user/username/projects/myproject"; const field = "fullscreen"; const fieldWithoutReadonly = `interface Document { ${field}: boolean; @@ -1166,7 +1161,7 @@ interface Document { const files = [aFile, libFileWithDocument]; function verifyLibErrors(options: CompilerOptions) { - const host = createWatchedSystem(files, { currentDirectory }); + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); const watch = createWatchOfFilesAndCompilerOptions([aFile.path], host, options); checkProgramActualFiles(watch(), [aFile.path, libFile.path]); checkOutputErrorsInitial(host, getErrors()); @@ -1202,7 +1197,7 @@ interface Document { describe("when non module file changes", () => { const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `${fieldWithoutReadonly} var y: number;` }; @@ -1211,7 +1206,7 @@ var y: number;` describe("when module file with global definitions changes", () => { const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `export {} declare global { ${fieldWithoutReadonly} @@ -1223,16 +1218,15 @@ var y: number; }); it("when skipLibCheck and skipDefaultLibCheck changes", () => { - const currentDirectory = "/user/username/projects/myproject"; const field = "fullscreen"; const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `interface Document { ${field}: boolean; }` }; const bFile: File = { - path: `${currentDirectory}/b.d.ts`, + path: `${projectRoot}/b.d.ts`, content: `interface Document { ${field}: boolean; }` @@ -1245,13 +1239,13 @@ interface Document { }` }; const configFile: File = { - path: `${currentDirectory}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: "{}" }; const files = [aFile, bFile, configFile, libFileWithDocument]; - const host = createWatchedSystem(files, { currentDirectory }); + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); const watch = createWatchOfConfigFile("tsconfig.json", host); verifyProgramFiles(); checkOutputErrorsInitial(host, [ @@ -1284,18 +1278,17 @@ interface Document { }); it("reports errors correctly with isolatedModules", () => { - const currentDirectory = "/user/username/projects/myproject"; const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `export const a: string = "";` }; const bFile: File = { - path: `${currentDirectory}/b.ts`, + path: `${projectRoot}/b.ts`, content: `import { a } from "./a"; const b: string = a;` }; const configFile: File = { - path: `${currentDirectory}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { isolatedModules: true @@ -1305,20 +1298,20 @@ const b: string = a;` const files = [aFile, bFile, libFile, configFile]; - const host = createWatchedSystem(files, { currentDirectory }); + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); const watch = createWatchOfConfigFile("tsconfig.json", host); verifyProgramFiles(); checkOutputErrorsInitial(host, emptyArray); - assert.equal(host.readFile(`${currentDirectory}/a.js`), `"use strict"; + assert.equal(host.readFile(`${projectRoot}/a.js`), `"use strict"; exports.__esModule = true; exports.a = ""; `, "Contents of a.js"); - assert.equal(host.readFile(`${currentDirectory}/b.js`), `"use strict"; + assert.equal(host.readFile(`${projectRoot}/b.js`), `"use strict"; exports.__esModule = true; var a_1 = require("./a"); var b = a_1.a; `, "Contents of b.js"); - const modifiedTime = host.getModifiedTime(`${currentDirectory}/b.js`); + const modifiedTime = host.getModifiedTime(`${projectRoot}/b.js`); host.writeFile(aFile.path, `export const a: number = 1`); host.runQueuedTimeoutCallbacks(); @@ -1326,11 +1319,11 @@ var b = a_1.a; checkOutputErrorsIncremental(host, [ getDiagnosticOfFileFromProgram(watch(), bFile.path, bFile.content.indexOf("b"), 1, Diagnostics.Type_0_is_not_assignable_to_type_1, "number", "string") ]); - assert.equal(host.readFile(`${currentDirectory}/a.js`), `"use strict"; + assert.equal(host.readFile(`${projectRoot}/a.js`), `"use strict"; exports.__esModule = true; exports.a = 1; `, "Contents of a.js"); - assert.equal(host.getModifiedTime(`${currentDirectory}/b.js`), modifiedTime, "Timestamp of b.js"); + assert.equal(host.getModifiedTime(`${projectRoot}/b.js`), modifiedTime, "Timestamp of b.js"); function verifyProgramFiles() { checkProgramActualFiles(watch(), [aFile.path, bFile.path, libFile.path]); @@ -1338,9 +1331,8 @@ exports.a = 1; }); it("reports errors correctly with file not in rootDir", () => { - const currentDirectory = "/user/username/projects/myproject"; const aFile: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `import { x } from "../b";` }; const bFile: File = { @@ -1348,7 +1340,7 @@ exports.a = 1; content: `export const x = 10;` }; const configFile: File = { - path: `${currentDirectory}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { rootDir: ".", @@ -1359,10 +1351,10 @@ exports.a = 1; const files = [aFile, bFile, libFile, configFile]; - const host = createWatchedSystem(files, { currentDirectory }); + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); const watch = createWatchOfConfigFile("tsconfig.json", host); checkOutputErrorsInitial(host, [ - getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.indexOf(`"../b"`), `"../b"`.length, Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, bFile.path, currentDirectory) + getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.indexOf(`"../b"`), `"../b"`.length, Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, bFile.path, projectRoot) ]); const aContent = ` @@ -1370,7 +1362,7 @@ ${aFile.content}`; host.writeFile(aFile.path, aContent); host.runQueuedTimeoutCallbacks(); checkOutputErrorsIncremental(host, [ - getDiagnosticOfFileFromProgram(watch(), aFile.path, aContent.indexOf(`"../b"`), `"../b"`.length, Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, bFile.path, currentDirectory) + getDiagnosticOfFileFromProgram(watch(), aFile.path, aContent.indexOf(`"../b"`), `"../b"`.length, Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, bFile.path, projectRoot) ]); }); }); diff --git a/src/testRunner/unittests/tscWatch/resolutionCache.ts b/src/testRunner/unittests/tscWatch/resolutionCache.ts index 802b9c5bc52..1c78c412a71 100644 --- a/src/testRunner/unittests/tscWatch/resolutionCache.ts +++ b/src/testRunner/unittests/tscWatch/resolutionCache.ts @@ -339,42 +339,40 @@ declare module "fs" { }); it("works when renaming node_modules folder that already contains @types folder", () => { - const currentDirectory = "/user/username/projects/myproject"; const file: File = { - path: `${currentDirectory}/a.ts`, + path: `${projectRoot}/a.ts`, content: `import * as q from "qqq";` }; const module: File = { - path: `${currentDirectory}/node_modules2/@types/qqq/index.d.ts`, + path: `${projectRoot}/node_modules2/@types/qqq/index.d.ts`, content: "export {}" }; const files = [file, module, libFile]; - const host = createWatchedSystem(files, { currentDirectory }); + const host = createWatchedSystem(files, { currentDirectory: projectRoot }); const watch = createWatchOfFilesAndCompilerOptions([file.path], host); checkProgramActualFiles(watch(), [file.path, libFile.path]); checkOutputErrorsInitial(host, [getDiagnosticModuleNotFoundOfFile(watch(), file, "qqq")]); checkWatchedDirectories(host, emptyArray, /*recursive*/ false); - checkWatchedDirectories(host, [`${currentDirectory}/node_modules`, `${currentDirectory}/node_modules/@types`], /*recursive*/ true); + checkWatchedDirectories(host, [`${projectRoot}/node_modules`, `${projectRoot}/node_modules/@types`], /*recursive*/ true); - host.renameFolder(`${currentDirectory}/node_modules2`, `${currentDirectory}/node_modules`); + host.renameFolder(`${projectRoot}/node_modules2`, `${projectRoot}/node_modules`); host.runQueuedTimeoutCallbacks(); - checkProgramActualFiles(watch(), [file.path, libFile.path, `${currentDirectory}/node_modules/@types/qqq/index.d.ts`]); + checkProgramActualFiles(watch(), [file.path, libFile.path, `${projectRoot}/node_modules/@types/qqq/index.d.ts`]); checkOutputErrorsIncremental(host, emptyArray); }); describe("ignores files/folder changes in node_modules that start with '.'", () => { - const projectPath = "/user/username/projects/project"; const npmCacheFile: File = { - path: `${projectPath}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`, + path: `${projectRoot}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`, content: JSON.stringify({ something: 10 }) }; const file1: File = { - path: `${projectPath}/test.ts`, + path: `${projectRoot}/test.ts`, content: `import { x } from "somemodule";` }; const file2: File = { - path: `${projectPath}/node_modules/somemodule/index.d.ts`, + path: `${projectRoot}/node_modules/somemodule/index.d.ts`, content: `export const x = 10;` }; const files = [libFile, file1, file2]; @@ -390,7 +388,7 @@ declare module "fs" { }); it("when watching node_modules as part of wild card directories in config project", () => { const config: File = { - path: `${projectPath}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: "{}" }; const host = createWatchedSystem(files.concat(config)); @@ -402,10 +400,50 @@ declare module "fs" { host.checkTimeoutQueueLength(0); }); }); + + it("when types in compiler option are global and installed at later point", () => { + const projectRoot = "/user/username/projects/myproject"; + const app: File = { + path: `${projectRoot}/lib/app.ts`, + content: `myapp.component("hello");` + }; + const tsconfig: File = { + path: `${projectRoot}/tsconfig.json`, + content: JSON.stringify({ + compilerOptions: { + module: "none", + types: ["@myapp/ts-types"] + } + }) + }; + const host = createWatchedSystem([app, tsconfig, libFile]); + const watch = createWatchOfConfigFile(tsconfig.path, host); + checkProgramActualFiles(watch(), [app.path, libFile.path]); + host.checkTimeoutQueueLength(0); + checkOutputErrorsInitial(host, [ + createCompilerDiagnostic(Diagnostics.Cannot_find_type_definition_file_for_0, "@myapp/ts-types") + ]); + + host.ensureFileOrFolder({ + path: `${projectRoot}/node_modules/@myapp/ts-types/package.json`, + content: JSON.stringify({ + version: "1.65.1", + types: "types/somefile.define.d.ts" + }) + }); + host.ensureFileOrFolder({ + path: `${projectRoot}/node_modules/@myapp/ts-types/types/somefile.define.d.ts`, + content: ` +declare namespace myapp { + function component(str: string): number; +}` + }); + host.checkTimeoutQueueLengthAndRun(1); + checkOutputErrorsIncremental(host, emptyArray); + }); }); describe("unittests:: tsc-watch:: resolutionCache:: tsc-watch with modules linked to sibling folder", () => { - const projectRoot = "/user/username/projects/project"; const mainPackageRoot = `${projectRoot}/main`; const linkedPackageRoot = `${projectRoot}/linked-package`; const mainFile: File = { diff --git a/src/testRunner/unittests/tscWatch/watchApi.ts b/src/testRunner/unittests/tscWatch/watchApi.ts index facd668b825..8f94ff005ec 100644 --- a/src/testRunner/unittests/tscWatch/watchApi.ts +++ b/src/testRunner/unittests/tscWatch/watchApi.ts @@ -1,6 +1,5 @@ namespace ts.tscWatch { describe("unittests:: tsc-watch:: watchAPI:: tsc-watch with custom module resolution", () => { - const projectRoot = "/user/username/projects/project"; const configFileJson: any = { compilerOptions: { module: "commonjs", resolveJsonModule: true }, files: ["index.ts"] @@ -39,7 +38,6 @@ namespace ts.tscWatch { }); describe("unittests:: tsc-watch:: watchAPI:: tsc-watch expose error count to watch status reporter", () => { - const projectRoot = "/user/username/projects/project"; const configFileJson: any = { compilerOptions: { module: "commonjs" }, files: ["index.ts"] diff --git a/src/testRunner/unittests/tsserver/compileOnSave.ts b/src/testRunner/unittests/tsserver/compileOnSave.ts index f641b6e85cb..47d4571541c 100644 --- a/src/testRunner/unittests/tsserver/compileOnSave.ts +++ b/src/testRunner/unittests/tsserver/compileOnSave.ts @@ -802,7 +802,6 @@ namespace ts.projectSystem { }); describe("unittests:: tsserver:: compileOnSave:: CompileOnSaveAffectedFileListRequest with and without projectFileName in request", () => { - const projectRoot = "/user/username/projects/myproject"; const core: File = { path: `${projectRoot}/core/core.ts`, content: "let z = 10;" diff --git a/src/testRunner/unittests/tsserver/configuredProjects.ts b/src/testRunner/unittests/tsserver/configuredProjects.ts index 7d066cd9473..5d2a8730492 100644 --- a/src/testRunner/unittests/tsserver/configuredProjects.ts +++ b/src/testRunner/unittests/tsserver/configuredProjects.ts @@ -82,7 +82,6 @@ namespace ts.projectSystem { }); it("add and then remove a config file in a folder with loose files", () => { - const projectRoot = "/user/username/projects/project"; const configFile: File = { path: `${projectRoot}/tsconfig.json`, content: `{ @@ -440,7 +439,6 @@ namespace ts.projectSystem { }); it("open file become a part of configured project if it is referenced from root file", () => { - const projectRoot = "/user/username/projects/project"; const file1 = { path: `${projectRoot}/a/b/f1.ts`, content: "export let x = 5" @@ -846,6 +844,67 @@ namespace ts.projectSystem { const edits = project.getLanguageService().getFormattingEditsForDocument(f1.path, options); assert.deepEqual(edits, [{ span: createTextSpan(/*start*/ 7, /*length*/ 3), newText: " " }]); }); + + it("when multiple projects are open, detects correct default project", () => { + const barConfig: File = { + path: `${projectRoot}/bar/tsconfig.json`, + content: JSON.stringify({ + include: ["index.ts"], + compilerOptions: { + lib: ["dom", "es2017"] + } + }) + }; + const barIndex: File = { + path: `${projectRoot}/bar/index.ts`, + content: ` +export function bar() { + console.log("hello world"); +}` + }; + const fooConfig: File = { + path: `${projectRoot}/foo/tsconfig.json`, + content: JSON.stringify({ + include: ["index.ts"], + compilerOptions: { + lib: ["es2017"] + } + }) + }; + const fooIndex: File = { + path: `${projectRoot}/foo/index.ts`, + content: ` +import { bar } from "bar"; +bar();` + }; + const barSymLink: SymLink = { + path: `${projectRoot}/foo/node_modules/bar`, + symLink: `${projectRoot}/bar` + }; + + const lib2017: File = { + path: `${getDirectoryPath(libFile.path)}/lib.es2017.d.ts`, + content: libFile.content + }; + const libDom: File = { + path: `${getDirectoryPath(libFile.path)}/lib.dom.d.ts`, + content: ` +declare var console: { + log(...args: any[]): void; +};` + }; + const host = createServerHost([barConfig, barIndex, fooConfig, fooIndex, barSymLink, lib2017, libDom]); + const session = createSession(host, { canUseEvents: true, }); + openFilesForSession([fooIndex, barIndex], session); + verifyGetErrRequest({ + session, + host, + expected: [ + { file: barIndex, syntax: [], semantic: [], suggestion: [] }, + { file: fooIndex, syntax: [], semantic: [], suggestion: [] }, + ] + }); + }); }); describe("unittests:: tsserver:: ConfiguredProjects:: non-existing directories listed in config file input array", () => { @@ -903,13 +962,12 @@ namespace ts.projectSystem { }); it("should tolerate invalid include files that start in subDirectory", () => { - const projectFolder = "/user/username/projects/myproject"; const f = { - path: `${projectFolder}/src/server/index.ts`, + path: `${projectRoot}/src/server/index.ts`, content: "let x = 1" }; const config = { - path: `${projectFolder}/src/server/tsconfig.json`, + path: `${projectRoot}/src/server/tsconfig.json`, content: JSON.stringify({ compiler: { module: "commonjs", diff --git a/src/testRunner/unittests/tsserver/documentRegistry.ts b/src/testRunner/unittests/tsserver/documentRegistry.ts index 10723300cc0..51b1bee6604 100644 --- a/src/testRunner/unittests/tsserver/documentRegistry.ts +++ b/src/testRunner/unittests/tsserver/documentRegistry.ts @@ -1,17 +1,16 @@ namespace ts.projectSystem { describe("unittests:: tsserver:: document registry in project service", () => { - const projectRootPath = "/user/username/projects/project"; const importModuleContent = `import {a} from "./module1"`; const file: File = { - path: `${projectRootPath}/index.ts`, + path: `${projectRoot}/index.ts`, content: importModuleContent }; const moduleFile: File = { - path: `${projectRootPath}/module1.d.ts`, + path: `${projectRoot}/module1.d.ts`, content: "export const a: number;" }; const configFile: File = { - path: `${projectRootPath}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: JSON.stringify({ files: ["index.ts"] }) }; diff --git a/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts b/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts index ff69a7e6568..cb9df9e6372 100644 --- a/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts +++ b/src/testRunner/unittests/tsserver/events/largeFileReferenced.ts @@ -1,6 +1,5 @@ namespace ts.projectSystem { describe("unittests:: tsserver:: events:: LargeFileReferencedEvent with large file", () => { - const projectRoot = "/user/username/projects/project"; function getLargeFile(useLargeTsFile: boolean) { return `src/large.${useLargeTsFile ? "ts" : "js"}`; diff --git a/src/testRunner/unittests/tsserver/events/projectLoading.ts b/src/testRunner/unittests/tsserver/events/projectLoading.ts index 5f4bf1a52c9..2bb0d95761a 100644 --- a/src/testRunner/unittests/tsserver/events/projectLoading.ts +++ b/src/testRunner/unittests/tsserver/events/projectLoading.ts @@ -1,16 +1,15 @@ namespace ts.projectSystem { describe("unittests:: tsserver:: events:: ProjectLoadingStart and ProjectLoadingFinish events", () => { - const projectRoot = "/user/username/projects"; const aTs: File = { - path: `${projectRoot}/a/a.ts`, + path: `${projects}/a/a.ts`, content: "export class A { }" }; const configA: File = { - path: `${projectRoot}/a/tsconfig.json`, + path: `${projects}/a/tsconfig.json`, content: "{}" }; - const bTsPath = `${projectRoot}/b/b.ts`; - const configBPath = `${projectRoot}/b/tsconfig.json`; + const bTsPath = `${projects}/b/b.ts`; + const configBPath = `${projects}/b/tsconfig.json`; const files = [libFile, aTs, configA]; function verifyProjectLoadingStartAndFinish(createSession: (host: TestServerHost) => { @@ -84,14 +83,14 @@ namespace ts.projectSystem { function verify(disableSourceOfProjectReferenceRedirect?: true) { const aDTs: File = { - path: `${projectRoot}/a/a.d.ts`, + path: `${projects}/a/a.d.ts`, content: `export declare class A { } //# sourceMappingURL=a.d.ts.map ` }; const aDTsMap: File = { - path: `${projectRoot}/a/a.d.ts.map`, + path: `${projects}/a/a.d.ts.map`, content: `{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["./a.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;CAAI"}` }; const bTs: File = { @@ -134,7 +133,7 @@ namespace ts.projectSystem { }); describe("with external projects and config files ", () => { - const projectFileName = `${projectRoot}/a/project.csproj`; + const projectFileName = `${projects}/a/project.csproj`; function createSession(lazyConfiguredProjectsFromExternalProject: boolean) { const { session, service, verifyEvent: verifyEventWorker, getNumberOfEvents } = createSessionToVerifyEvent(files); diff --git a/src/testRunner/unittests/tsserver/externalProjects.ts b/src/testRunner/unittests/tsserver/externalProjects.ts index 21d1290fc2e..5e335f1a4fa 100644 --- a/src/testRunner/unittests/tsserver/externalProjects.ts +++ b/src/testRunner/unittests/tsserver/externalProjects.ts @@ -824,10 +824,9 @@ namespace ts.projectSystem { }); it("handles creation of external project with jsconfig before jsconfig creation watcher is invoked", () => { - const projectLocation = `/user/username/projects/WebApplication36/WebApplication36`; - const projectFileName = `${projectLocation}/WebApplication36.csproj`; + const projectFileName = `${projectRoot}/WebApplication36.csproj`; const tsconfig: File = { - path: `${projectLocation}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: "{}" }; const files = [libFile, tsconfig]; @@ -845,7 +844,7 @@ namespace ts.projectSystem { checkProjectActualFiles(configProject, [tsconfig.path]); // write js file, open external project and open it for edit - const jsFilePath = `${projectLocation}/javascript.js`; + const jsFilePath = `${projectRoot}/javascript.js`; host.writeFile(jsFilePath, ""); service.openExternalProjects([{ projectFileName, @@ -860,7 +859,7 @@ namespace ts.projectSystem { // write jsconfig file const jsConfig: File = { - path: `${projectLocation}/jsconfig.json`, + path: `${projectRoot}/jsconfig.json`, content: "{}" }; // Dont invoke file creation watchers as the repro suggests diff --git a/src/testRunner/unittests/tsserver/inferredProjects.ts b/src/testRunner/unittests/tsserver/inferredProjects.ts index 44ff8292acd..6c647c4e641 100644 --- a/src/testRunner/unittests/tsserver/inferredProjects.ts +++ b/src/testRunner/unittests/tsserver/inferredProjects.ts @@ -1,7 +1,6 @@ namespace ts.projectSystem { describe("unittests:: tsserver:: Inferred projects", () => { it("create inferred project", () => { - const projectRoot = "/user/username/projects/project"; const appFile: File = { path: `${projectRoot}/app.ts`, content: ` @@ -31,7 +30,6 @@ namespace ts.projectSystem { }); it("should use only one inferred project if 'useOneInferredProject' is set", () => { - const projectRoot = "/user/username/projects/project"; const file1 = { path: `${projectRoot}/a/b/main.ts`, content: "let x =1;" @@ -347,7 +345,6 @@ namespace ts.projectSystem { }); it("should still retain configured project created while opening the file", () => { - const projectRoot = "/user/username/projects/project"; const appFile: File = { path: `${projectRoot}/app.ts`, content: `const app = 20;` diff --git a/src/testRunner/unittests/tsserver/projectErrors.ts b/src/testRunner/unittests/tsserver/projectErrors.ts index bb60e48e3ad..f5c28eb7a74 100644 --- a/src/testRunner/unittests/tsserver/projectErrors.ts +++ b/src/testRunner/unittests/tsserver/projectErrors.ts @@ -292,42 +292,21 @@ namespace ts.projectSystem { // Since this is not js project so no typings are queued host.checkTimeoutQueueLength(0); - const newTimeoutId = host.getNextTimeoutId(); - const expectedSequenceId = session.getNextSeq(); - session.executeCommandSeq({ - command: server.CommandNames.Geterr, - arguments: { - delay: 0, - files: [untitledFile] - } - }); - host.checkTimeoutQueueLength(1); - - // Run the last one = get error request - host.runQueuedTimeoutCallbacks(newTimeoutId); - - assert.isFalse(hasError()); - host.checkTimeoutQueueLength(0); - checkErrorMessage(session, "syntaxDiag", { file: untitledFile, diagnostics: [] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(); - assert.isFalse(hasError()); const errorOffset = fileContent.indexOf(refPathNotFound1) + 1; - checkErrorMessage(session, "semanticDiag", { - file: untitledFile, - diagnostics: [ - createDiagnostic({ line: 1, offset: errorOffset }, { line: 1, offset: errorOffset + refPathNotFound1.length }, Diagnostics.File_0_not_found, [refPathNotFound1], "error"), - createDiagnostic({ line: 2, offset: errorOffset }, { line: 2, offset: errorOffset + refPathNotFound2.length }, Diagnostics.File_0_not_found, [refPathNotFound2.substr(2)], "error") - ] + verifyGetErrRequest({ + session, + host, + expected: [{ + file: untitledFile, + syntax: [], + semantic: [ + createDiagnostic({ line: 1, offset: errorOffset }, { line: 1, offset: errorOffset + refPathNotFound1.length }, Diagnostics.File_0_not_found, [refPathNotFound1], "error"), + createDiagnostic({ line: 2, offset: errorOffset }, { line: 2, offset: errorOffset + refPathNotFound2.length }, Diagnostics.File_0_not_found, [refPathNotFound2.substr(2)], "error") + ], + suggestion: [] + }], + onErrEvent: () => assert.isFalse(hasError()) }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - assert.isFalse(hasError()); - checkErrorMessage(session, "suggestionDiag", { file: untitledFile, diagnostics: [] }); - checkCompleteEvent(session, 2, expectedSequenceId); - session.clearMessages(); } it("has projectRoot", () => { @@ -371,27 +350,16 @@ namespace ts.projectSystem { verifyErrorsInApp(); function verifyErrorsInApp() { - session.clearMessages(); - const expectedSequenceId = session.getNextSeq(); - session.executeCommandSeq({ - command: server.CommandNames.Geterr, - arguments: { - delay: 0, - files: [app.path] - } + verifyGetErrRequest({ + session, + host, + expected: [{ + file: app, + syntax: [], + semantic: [], + suggestion: [] + }], }); - host.checkTimeoutQueueLengthAndRun(1); - checkErrorMessage(session, "syntaxDiag", { file: app.path, diagnostics: [] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(); - checkErrorMessage(session, "semanticDiag", { file: app.path, diagnostics: [] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - checkErrorMessage(session, "suggestionDiag", { file: app.path, diagnostics: [] }); - checkCompleteEvent(session, 2, expectedSequenceId); - session.clearMessages(); } }); @@ -421,7 +389,6 @@ namespace ts.projectSystem { }); it("Reports errors correctly when file referenced by inferred project root, is opened right after closing the root file", () => { - const projectRoot = "/user/username/projects/myproject"; const app: File = { path: `${projectRoot}/src/client/app.js`, content: "" @@ -451,32 +418,12 @@ namespace ts.projectSystem { checkErrors([serverUtilities.path, app.path]); function checkErrors(openFiles: [string, string]) { - const expectedSequenceId = session.getNextSeq(); - session.executeCommandSeq({ - command: protocol.CommandTypes.Geterr, - arguments: { - delay: 0, - files: openFiles - } + verifyGetErrRequest({ + session, + host, + expected: openFiles.map(file => ({ file, syntax: [], semantic: [], suggestion: [] })), + existingTimeouts: 2 }); - - for (const openFile of openFiles) { - session.clearMessages(); - host.checkTimeoutQueueLength(3); - host.runQueuedTimeoutCallbacks(host.getNextTimeoutId() - 1); - - checkErrorMessage(session, "syntaxDiag", { file: openFile, diagnostics: [] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(); - checkErrorMessage(session, "semanticDiag", { file: openFile, diagnostics: [] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - checkErrorMessage(session, "suggestionDiag", { file: openFile, diagnostics: [] }); - } - checkCompleteEvent(session, 2, expectedSequenceId); - session.clearMessages(); } }); @@ -531,36 +478,19 @@ declare module '@custom/plugin' { function checkErrors() { host.checkTimeoutQueueLength(0); - const expectedSequenceId = session.getNextSeq(); - session.executeCommandSeq({ - command: server.CommandNames.Geterr, - arguments: { - delay: 0, - files: [aFile.path], - } + verifyGetErrRequest({ + session, + host, + expected: [{ + file: aFile, + syntax: [], + semantic: [], + suggestion: [ + createDiagnostic({ line: 1, offset: 1 }, { line: 1, offset: 44 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["myModule"], "suggestion", /*reportsUnnecessary*/ true), + createDiagnostic({ line: 2, offset: 10 }, { line: 2, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["foo"], "suggestion", /*reportsUnnecessary*/ true) + ] + }] }); - - host.checkTimeoutQueueLengthAndRun(1); - - checkErrorMessage(session, "syntaxDiag", { file: aFile.path, diagnostics: [] }, /*isMostRecent*/ true); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - - checkErrorMessage(session, "semanticDiag", { file: aFile.path, diagnostics: [] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - - checkErrorMessage(session, "suggestionDiag", { - file: aFile.path, - diagnostics: [ - createDiagnostic({ line: 1, offset: 1 }, { line: 1, offset: 44 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["myModule"], "suggestion", /*reportsUnnecessary*/ true), - createDiagnostic({ line: 2, offset: 10 }, { line: 2, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["foo"], "suggestion", /*reportsUnnecessary*/ true) - ], - }); - checkCompleteEvent(session, 2, expectedSequenceId); - session.clearMessages(); } }); }); diff --git a/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts b/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts index 9602ef6360e..7399078f1ef 100644 --- a/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts +++ b/src/testRunner/unittests/tsserver/projectReferenceCompileOnSave.ts @@ -1,8 +1,7 @@ namespace ts.projectSystem { describe("unittests:: tsserver:: with project references and compile on save", () => { - const projectLocation = "/user/username/projects/myproject"; - const dependecyLocation = `${projectLocation}/dependency`; - const usageLocation = `${projectLocation}/usage`; + const dependecyLocation = `${projectRoot}/dependency`; + const usageLocation = `${projectRoot}/usage`; const dependencyTs: File = { path: `${dependecyLocation}/fns.ts`, content: `export function fn1() { } @@ -294,7 +293,7 @@ exports.fn2 = fn2; ${appendJs}` }, { - path: `${projectLocation}/decls/fns.d.ts`, + path: `${projectRoot}/decls/fns.d.ts`, content: `export declare function fn1(): void; export declare function fn2(): void; ${appendDts}` diff --git a/src/testRunner/unittests/tsserver/projectReferenceErrors.ts b/src/testRunner/unittests/tsserver/projectReferenceErrors.ts index a3ec4848615..e6e71263576 100644 --- a/src/testRunner/unittests/tsserver/projectReferenceErrors.ts +++ b/src/testRunner/unittests/tsserver/projectReferenceErrors.ts @@ -1,48 +1,92 @@ namespace ts.projectSystem { - describe("unittests:: tsserver:: with project references and error reporting", () => { - const projectLocation = "/user/username/projects/myproject"; - const dependecyLocation = `${projectLocation}/dependency`; - const usageLocation = `${projectLocation}/usage`; + export interface GetErrDiagnostics { + file: string | File; + syntax?: protocol.Diagnostic[]; + semantic?: protocol.Diagnostic[]; + suggestion?: protocol.Diagnostic[]; + } + export interface VerifyGetErrRequestBase { + session: TestSession; + host: TestServerHost; + onErrEvent?: () => void; + existingTimeouts?: number; + } + export interface VerifyGetErrRequest extends VerifyGetErrRequestBase { + expected: readonly GetErrDiagnostics[]; + } + export function verifyGetErrRequest(request: VerifyGetErrRequest) { + const { session, expected } = request; + session.clearMessages(); + const expectedSequenceId = session.getNextSeq(); + session.executeCommandSeq({ + command: protocol.CommandTypes.Geterr, + arguments: { + delay: 0, + files: expected.map(f => filePath(f.file)) + } + }); + checkAllErrors({ ...request, expectedSequenceId }); + } - interface CheckErrorsInFile { - session: TestSession; - host: TestServerHost; - expected: GetErrDiagnostics; - expectedSequenceId?: number; + export interface CheckAllErrors extends VerifyGetErrRequest { + expectedSequenceId: number; + } + function checkAllErrors({ expected, expectedSequenceId, ...rest }: CheckAllErrors) { + for (let i = 0; i < expected.length; i++) { + checkErrorsInFile({ + ...rest, + expected: expected[i], + expectedSequenceId: i === expected.length - 1 ? expectedSequenceId : undefined, + }); } - function checkErrorsInFile({ session, host, expected: { file, syntax, semantic, suggestion }, expectedSequenceId }: CheckErrorsInFile) { + } + + function filePath(file: string | File) { + return isString(file) ? file : file.path; + } + interface CheckErrorsInFile extends VerifyGetErrRequestBase { + expected: GetErrDiagnostics; + expectedSequenceId?: number; + } + function checkErrorsInFile({ + session, host, onErrEvent, existingTimeouts, expectedSequenceId, + expected: { file, syntax, semantic, suggestion }, + }: CheckErrorsInFile) { + onErrEvent = onErrEvent || noop; + if (existingTimeouts !== undefined) { + host.checkTimeoutQueueLength(existingTimeouts + 1); + host.runQueuedTimeoutCallbacks(host.getNextTimeoutId() - 1); + } + else { host.checkTimeoutQueueLengthAndRun(1); - checkErrorMessage(session, "syntaxDiag", { file: file.path, diagnostics: syntax }); + } + if (syntax) { + onErrEvent(); + checkErrorMessage(session, "syntaxDiag", { file: filePath(file), diagnostics: syntax }); + } + if (semantic) { session.clearMessages(); host.runQueuedImmediateCallbacks(1); - checkErrorMessage(session, "semanticDiag", { file: file.path, diagnostics: semantic }); + onErrEvent(); + checkErrorMessage(session, "semanticDiag", { file: filePath(file), diagnostics: semantic }); + } + if (suggestion) { session.clearMessages(); host.runQueuedImmediateCallbacks(1); - checkErrorMessage(session, "suggestionDiag", { file: file.path, diagnostics: suggestion }); - if (expectedSequenceId !== undefined) { - checkCompleteEvent(session, 2, expectedSequenceId); - } - session.clearMessages(); + onErrEvent(); + checkErrorMessage(session, "suggestionDiag", { file: filePath(file), diagnostics: suggestion }); } + if (expectedSequenceId !== undefined) { + checkCompleteEvent(session, syntax || semantic || suggestion ? 2 : 1, expectedSequenceId); + } + session.clearMessages(); + } - interface CheckAllErrors { - session: TestSession; - host: TestServerHost; - expected: readonly GetErrDiagnostics[]; - expectedSequenceId: number; - } - function checkAllErrors({ session, host, expected, expectedSequenceId }: CheckAllErrors) { - for (let i = 0; i < expected.length; i++) { - checkErrorsInFile({ - session, - host, - expected: expected[i], - expectedSequenceId: i === expected.length - 1 ? expectedSequenceId : undefined - }); - } - } + describe("unittests:: tsserver:: with project references and error reporting", () => { + const dependecyLocation = `${projectRoot}/dependency`; + const usageLocation = `${projectRoot}/usage`; function verifyErrorsUsingGeterr({ allFiles, openFiles, expectedGetErr }: VerifyScenario) { it("verifies the errors in open file", () => { @@ -50,18 +94,7 @@ namespace ts.projectSystem { const session = createSession(host, { canUseEvents: true, }); openFilesForSession(openFiles(), session); - session.clearMessages(); - const expectedSequenceId = session.getNextSeq(); - const expected = expectedGetErr(); - session.executeCommandSeq({ - command: protocol.CommandTypes.Geterr, - arguments: { - delay: 0, - files: expected.map(f => f.file.path) - } - }); - - checkAllErrors({ session, host, expected, expectedSequenceId }); + verifyGetErrRequest({ session, host, expected: expectedGetErr() }); }); } @@ -96,27 +129,27 @@ namespace ts.projectSystem { const actualSyntax = session.executeCommandSeq({ command: protocol.CommandTypes.SyntacticDiagnosticsSync, arguments: { - file: file.path, + file: filePath(file), projectFileName: project } }).response as protocol.Diagnostic[]; - assert.deepEqual(actualSyntax, syntax, `Syntax diagnostics for file: ${file.path}, project: ${project}`); + assert.deepEqual(actualSyntax, syntax, `Syntax diagnostics for file: ${filePath(file)}, project: ${project}`); const actualSemantic = session.executeCommandSeq({ command: protocol.CommandTypes.SemanticDiagnosticsSync, arguments: { - file: file.path, + file: filePath(file), projectFileName: project } }).response as protocol.Diagnostic[]; - assert.deepEqual(actualSemantic, semantic, `Semantic diagnostics for file: ${file.path}, project: ${project}`); + assert.deepEqual(actualSemantic, semantic, `Semantic diagnostics for file: ${filePath(file)}, project: ${project}`); const actualSuggestion = session.executeCommandSeq({ command: protocol.CommandTypes.SuggestionDiagnosticsSync, arguments: { - file: file.path, + file: filePath(file), projectFileName: project } }).response as protocol.Diagnostic[]; - assert.deepEqual(actualSuggestion, suggestion, `Suggestion diagnostics for file: ${file.path}, project: ${project}`); + assert.deepEqual(actualSuggestion, suggestion, `Suggestion diagnostics for file: ${filePath(file)}, project: ${project}`); } }); } @@ -140,12 +173,6 @@ namespace ts.projectSystem { }); } - interface GetErrDiagnostics { - file: File; - syntax: protocol.Diagnostic[]; - semantic: protocol.Diagnostic[]; - suggestion: protocol.Diagnostic[]; - } interface GetErrForProjectDiagnostics { project: string; errors: readonly GetErrDiagnostics[]; diff --git a/src/testRunner/unittests/tsserver/projectReferences.ts b/src/testRunner/unittests/tsserver/projectReferences.ts index e4716ac5f2e..bbc368b6d8a 100644 --- a/src/testRunner/unittests/tsserver/projectReferences.ts +++ b/src/testRunner/unittests/tsserver/projectReferences.ts @@ -92,10 +92,9 @@ namespace ts.projectSystem { }); describe("with main and depedency project", () => { - const projectLocation = "/user/username/projects/myproject"; - const dependecyLocation = `${projectLocation}/dependency`; - const dependecyDeclsLocation = `${projectLocation}/decls`; - const mainLocation = `${projectLocation}/main`; + const dependecyLocation = `${projectRoot}/dependency`; + const dependecyDeclsLocation = `${projectRoot}/decls`; + const mainLocation = `${projectRoot}/main`; const dependencyTs: File = { path: `${dependecyLocation}/FnS.ts`, content: `export function fn1() { } @@ -137,11 +136,11 @@ fn5(); }; const randomFile: File = { - path: `${projectLocation}/random/random.ts`, + path: `${projectRoot}/random/random.ts`, content: "let a = 10;" }; const randomConfig: File = { - path: `${projectLocation}/random/tsconfig.json`, + path: `${projectRoot}/random/tsconfig.json`, content: "{}" }; const dtsLocation = `${dependecyDeclsLocation}/FnS.d.ts`; @@ -1302,9 +1301,8 @@ function foo() { }); it("reusing d.ts files from composite and non composite projects", () => { - const projectLocation = "/user/username/projects/myproject"; const configA: File = { - path: `${projectLocation}/compositea/tsconfig.json`, + path: `${projectRoot}/compositea/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, @@ -1316,27 +1314,27 @@ function foo() { }) }; const aTs: File = { - path: `${projectLocation}/compositea/a.ts`, + path: `${projectRoot}/compositea/a.ts`, content: `import { b } from "@ref/compositeb/b";` }; const a2Ts: File = { - path: `${projectLocation}/compositea/a2.ts`, + path: `${projectRoot}/compositea/a2.ts`, content: `export const x = 10;` }; const configB: File = { - path: `${projectLocation}/compositeb/tsconfig.json`, + path: `${projectRoot}/compositeb/tsconfig.json`, content: configA.content }; const bTs: File = { - path: `${projectLocation}/compositeb/b.ts`, + path: `${projectRoot}/compositeb/b.ts`, content: "export function b() {}" }; const bDts: File = { - path: `${projectLocation}/dist/compositeb/b.d.ts`, + path: `${projectRoot}/dist/compositeb/b.d.ts`, content: "export declare function b(): void;" }; const configC: File = { - path: `${projectLocation}/compositec/tsconfig.json`, + path: `${projectRoot}/compositec/tsconfig.json`, content: JSON.stringify({ compilerOptions: { composite: true, @@ -1349,7 +1347,7 @@ function foo() { }) }; const cTs: File = { - path: `${projectLocation}/compositec/c.ts`, + path: `${projectRoot}/compositec/c.ts`, content: aTs.content }; const files = [libFile, aTs, a2Ts, configA, bDts, bTs, configB, cTs, configC]; diff --git a/src/testRunner/unittests/tsserver/projects.ts b/src/testRunner/unittests/tsserver/projects.ts index 7d92949b526..56bbe989bfc 100644 --- a/src/testRunner/unittests/tsserver/projects.ts +++ b/src/testRunner/unittests/tsserver/projects.ts @@ -1209,17 +1209,16 @@ var x = 10;` }); it("requests are done on file on pendingReload but has svc for previous version", () => { - const projectLocation = "/user/username/projects/project"; const file1: File = { - path: `${projectLocation}/src/file1.ts`, + path: `${projectRoot}/src/file1.ts`, content: `import { y } from "./file2"; let x = 10;` }; const file2: File = { - path: `${projectLocation}/src/file2.ts`, + path: `${projectRoot}/src/file2.ts`, content: "export let y = 10;" }; const config: File = { - path: `${projectLocation}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: "{}" }; const files = [file1, file2, libFile, config]; @@ -1309,20 +1308,19 @@ var x = 10;` }); it("Orphan source files are handled correctly on watch trigger", () => { - const projectLocation = "/user/username/projects/project"; const file1: File = { - path: `${projectLocation}/src/file1.ts`, + path: `${projectRoot}/src/file1.ts`, content: `export let x = 10;` }; const file2: File = { - path: `${projectLocation}/src/file2.ts`, + path: `${projectRoot}/src/file2.ts`, content: "export let y = 10;" }; const configContent1 = JSON.stringify({ files: ["src/file1.ts", "src/file2.ts"] }); const config: File = { - path: `${projectLocation}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: configContent1 }; const files = [file1, file2, libFile, config]; @@ -1445,36 +1443,17 @@ var x = 10;` // Actually trigger the file move host.reloadFS(files); host.checkTimeoutQueueLength(2); - const fileBErrorTimeoutId = host.getNextTimeoutId(); - session.executeCommandSeq({ - command: protocol.CommandTypes.Geterr, - arguments: { - files: [fileB.path, fileSubA.path], - delay: 0 - } + verifyGetErrRequest({ + session, + host, + expected: [ + { file: fileB, syntax: [], semantic: [], suggestion: [] }, + { file: fileSubA }, + ], + existingTimeouts: 2, + onErrEvent: () => assert.isFalse(hasErrorMsg()) }); - const getErrSeqId = session.getSeq(); - host.checkTimeoutQueueLength(3); - - session.clearMessages(); - host.runQueuedTimeoutCallbacks(fileBErrorTimeoutId); - checkErrorMessage(session, "syntaxDiag", { file: fileB.path, diagnostics: [] }); - - session.clearMessages(); - host.runQueuedImmediateCallbacks(); - checkErrorMessage(session, "semanticDiag", { file: fileB.path, diagnostics: [] }); - - session.clearMessages(); - const fileSubAErrorTimeoutId = host.getNextTimeoutId(); - host.runQueuedImmediateCallbacks(); - checkErrorMessage(session, "suggestionDiag", { file: fileB.path, diagnostics: [] }); - - session.clearMessages(); - host.checkTimeoutQueueLength(3); - host.runQueuedTimeoutCallbacks(fileSubAErrorTimeoutId); - checkCompleteEvent(session, 1, getErrSeqId); - assert.isFalse(hasErrorMsg()); function openFile(file: File) { openFilesForSession([{ file, projectRootPath }], session); diff --git a/src/testRunner/unittests/tsserver/resolutionCache.ts b/src/testRunner/unittests/tsserver/resolutionCache.ts index 85af2bb36b0..7ebb2ee4d37 100644 --- a/src/testRunner/unittests/tsserver/resolutionCache.ts +++ b/src/testRunner/unittests/tsserver/resolutionCache.ts @@ -149,34 +149,20 @@ namespace ts.projectSystem { } }); checkNumberOfProjects(service, { inferredProjects: 1 }); - session.clearMessages(); - const expectedSequenceId = session.getNextSeq(); - session.executeCommandSeq({ - command: server.CommandNames.Geterr, - arguments: { - delay: 0, - files: [file1.path] - } - }); - host.checkTimeoutQueueLengthAndRun(1); - checkErrorMessage(session, "syntaxDiag", { file: file1.path, diagnostics: [] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(); const startOffset = file1.content.indexOf('"') + 1; - checkErrorMessage(session, "semanticDiag", { - file: file1.path, - diagnostics: [ - createDiagnostic({ line: 1, offset: startOffset }, { line: 1, offset: startOffset + '"pad"'.length }, Diagnostics.Cannot_find_module_0, ["pad"]) - ], + verifyGetErrRequest({ + session, + host, + expected: [{ + file: file1, + syntax: [], + semantic: [ + createDiagnostic({ line: 1, offset: startOffset }, { line: 1, offset: startOffset + '"pad"'.length }, Diagnostics.Cannot_find_module_0, ["pad"]) + ], + suggestion: [] + }] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - checkErrorMessage(session, "suggestionDiag", { file: file1.path, diagnostics: [] }); - checkCompleteEvent(session, 2, expectedSequenceId); - session.clearMessages(); const padIndex: File = { path: `${folderPath}/node_modules/@types/pad/index.d.ts`, @@ -213,40 +199,22 @@ namespace ts.projectSystem { checkNumberOfProjects(service, { inferredProjects: 1 }); session.clearMessages(); - const expectedSequenceId = session.getNextSeq(); host.checkTimeoutQueueLengthAndRun(2); checkProjectUpdatedInBackgroundEvent(session, [file.path]); - session.clearMessages(); - session.executeCommandSeq({ - command: server.CommandNames.Geterr, - arguments: { - delay: 0, - files: [file.path], - } + verifyGetErrRequest({ + session, + host, + expected: [{ + file, + syntax: [], + semantic: [], + suggestion: [ + createDiagnostic({ line: 1, offset: 12 }, { line: 1, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["p"], "suggestion", /*reportsUnnecessary*/ true), + ] + }] }); - - host.checkTimeoutQueueLengthAndRun(1); - - checkErrorMessage(session, "syntaxDiag", { file: file.path, diagnostics: [] }, /*isMostRecent*/ true); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - - checkErrorMessage(session, "semanticDiag", { file: file.path, diagnostics: [] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - - checkErrorMessage(session, "suggestionDiag", { - file: file.path, - diagnostics: [ - createDiagnostic({ line: 1, offset: 12 }, { line: 1, offset: 13 }, Diagnostics._0_is_declared_but_its_value_is_never_read, ["p"], "suggestion", /*reportsUnnecessary*/ true), - ], - }); - checkCompleteEvent(session, 2, expectedSequenceId); - session.clearMessages(); }); it("disable suggestion diagnostics", () => { @@ -273,31 +241,19 @@ namespace ts.projectSystem { checkNumberOfProjects(service, { inferredProjects: 1 }); session.clearMessages(); - const expectedSequenceId = session.getNextSeq(); host.checkTimeoutQueueLengthAndRun(2); checkProjectUpdatedInBackgroundEvent(session, [file.path]); - session.clearMessages(); - session.executeCommandSeq({ - command: server.CommandNames.Geterr, - arguments: { - delay: 0, - files: [file.path], - } + verifyGetErrRequest({ + session, + host, + expected: [{ + file, + syntax: [], + semantic: [] + }] }); - - host.checkTimeoutQueueLengthAndRun(1); - - checkErrorMessage(session, "syntaxDiag", { file: file.path, diagnostics: [] }, /*isMostRecent*/ true); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - - checkErrorMessage(session, "semanticDiag", { file: file.path, diagnostics: [] }); - // No suggestion event, we're done. - checkCompleteEvent(session, 2, expectedSequenceId); - session.clearMessages(); }); it("suppressed diagnostic events", () => { @@ -494,9 +450,8 @@ namespace ts.projectSystem { }); describe("unittests:: tsserver:: resolutionCache:: tsserverProjectSystem module resolution caching", () => { - const projectLocation = "/user/username/projects/myproject"; const configFile: File = { - path: `${projectLocation}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: JSON.stringify({ compilerOptions: { traceResolution: true } }) }; @@ -603,7 +558,7 @@ namespace ts.projectSystem { } function verifyWatchesWithConfigFile(host: TestServerHost, files: File[], openFile: File, extraExpectedDirectories?: readonly string[]) { - const expectedRecursiveDirectories = arrayToSet([projectLocation, `${projectLocation}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)]); + const expectedRecursiveDirectories = arrayToSet([projectRoot, `${projectRoot}/${nodeModulesAtTypes}`, ...(extraExpectedDirectories || emptyArray)]); checkWatchedFiles(host, mapDefined(files, f => { if (f === openFile) { return undefined; @@ -622,11 +577,11 @@ namespace ts.projectSystem { describe("from files in same folder", () => { function getFiles(fileContent: string) { const file1: File = { - path: `${projectLocation}/src/file1.ts`, + path: `${projectRoot}/src/file1.ts`, content: fileContent }; const file2: File = { - path: `${projectLocation}/src/file2.ts`, + path: `${projectRoot}/src/file2.ts`, content: fileContent }; return { file1, file2 }; @@ -637,7 +592,7 @@ namespace ts.projectSystem { const module2Name = "../module2"; const fileContent = `import { module1 } from "${module1Name}";import { module2 } from "${module2Name}";`; const { file1, file2 } = getFiles(fileContent); - const { module1, module2 } = getModules(`${projectLocation}/src/module1.ts`, `${projectLocation}/module2.ts`); + const { module1, module2 } = getModules(`${projectRoot}/src/module1.ts`, `${projectRoot}/module2.ts`); const files = [module1, module2, file1, file2, configFile, libFile]; const host = createServerHost(files); const resolutionTrace = createHostModuleResolutionTrace(host); @@ -660,12 +615,12 @@ namespace ts.projectSystem { }); it("non relative module name", () => { - const expectedNonRelativeDirectories = [`${projectLocation}/node_modules`, `${projectLocation}/src`]; + const expectedNonRelativeDirectories = [`${projectRoot}/node_modules`, `${projectRoot}/src`]; const module1Name = "module1"; const module2Name = "module2"; const fileContent = `import { module1 } from "${module1Name}";import { module2 } from "${module2Name}";`; const { file1, file2 } = getFiles(fileContent); - const { module1, module2 } = getModules(`${projectLocation}/src/node_modules/module1/index.ts`, `${projectLocation}/node_modules/module2/index.ts`); + const { module1, module2 } = getModules(`${projectRoot}/src/node_modules/module1/index.ts`, `${projectRoot}/node_modules/module2/index.ts`); const files = [module1, module2, file1, file2, configFile, libFile]; const host = createServerHost(files); const resolutionTrace = createHostModuleResolutionTrace(host); @@ -691,19 +646,19 @@ namespace ts.projectSystem { describe("from files in different folders", () => { function getFiles(fileContent1: string, fileContent2 = fileContent1, fileContent3 = fileContent1, fileContent4 = fileContent1) { const file1: File = { - path: `${projectLocation}/product/src/file1.ts`, + path: `${projectRoot}/product/src/file1.ts`, content: fileContent1 }; const file2: File = { - path: `${projectLocation}/product/src/feature/file2.ts`, + path: `${projectRoot}/product/src/feature/file2.ts`, content: fileContent2 }; const file3: File = { - path: `${projectLocation}/product/test/src/file3.ts`, + path: `${projectRoot}/product/test/src/file3.ts`, content: fileContent3 }; const file4: File = { - path: `${projectLocation}/product/test/file4.ts`, + path: `${projectRoot}/product/test/file4.ts`, content: fileContent4 }; return { file1, file2, file3, file4 }; @@ -721,7 +676,7 @@ namespace ts.projectSystem { const fileContent3 = `import { module1 } from "${module5Name}";import { module2 } from "${module4Name}";`; const fileContent4 = `import { module1 } from "${module6Name}";import { module2 } from "${module2Name}";`; const { file1, file2, file3, file4 } = getFiles(fileContent1, fileContent2, fileContent3, fileContent4); - const { module1, module2 } = getModules(`${projectLocation}/product/src/module1.ts`, `${projectLocation}/product/module2.ts`); + const { module1, module2 } = getModules(`${projectRoot}/product/src/module1.ts`, `${projectRoot}/product/module2.ts`); const files = [module1, module2, file1, file2, file3, file4, configFile, libFile]; const host = createServerHost(files); const resolutionTrace = createHostModuleResolutionTrace(host); @@ -753,12 +708,12 @@ namespace ts.projectSystem { }); it("non relative module name", () => { - const expectedNonRelativeDirectories = [`${projectLocation}/node_modules`, `${projectLocation}/product`]; + const expectedNonRelativeDirectories = [`${projectRoot}/node_modules`, `${projectRoot}/product`]; const module1Name = "module1"; const module2Name = "module2"; const fileContent = `import { module1 } from "${module1Name}";import { module2 } from "${module2Name}";`; const { file1, file2, file3, file4 } = getFiles(fileContent); - const { module1, module2 } = getModules(`${projectLocation}/product/node_modules/module1/index.ts`, `${projectLocation}/node_modules/module2/index.ts`); + const { module1, module2 } = getModules(`${projectRoot}/product/node_modules/module1/index.ts`, `${projectRoot}/node_modules/module2/index.ts`); const files = [module1, module2, file1, file2, file3, file4, configFile, libFile]; const host = createServerHost(files); const resolutionTrace = createHostModuleResolutionTrace(host); @@ -768,8 +723,8 @@ namespace ts.projectSystem { getExpectedNonRelativeModuleResolutionTrace(host, file1, module2, module2Name, expectedTrace); getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file2, module1, module1Name, getDirectoryPath(file1.path), expectedTrace); getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file2, module2, module2Name, getDirectoryPath(file1.path), expectedTrace); - getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file4, module1, module1Name, `${projectLocation}/product`, expectedTrace); - getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file4, module2, module2Name, `${projectLocation}/product`, expectedTrace); + getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file4, module1, module1Name, `${projectRoot}/product`, expectedTrace); + getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file4, module2, module2Name, `${projectRoot}/product`, expectedTrace); getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file3, module1, module1Name, getDirectoryPath(file4.path), expectedTrace); getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file3, module2, module2Name, getDirectoryPath(file4.path), expectedTrace); verifyTrace(resolutionTrace, expectedTrace); @@ -797,7 +752,7 @@ namespace ts.projectSystem { const file4Name = "../test/file4"; const importModuleContent = `import { module1 } from "${module1Name}";import { module2 } from "${module2Name}";`; const { file1, file2, file3, file4 } = getFiles(`import "${file2Name}"; import "${file4Name}"; import "${file3Name}"; ${importModuleContent}`, importModuleContent, importModuleContent, importModuleContent); - const { module1, module2 } = getModules(`${projectLocation}/product/node_modules/module1/index.ts`, `${projectLocation}/node_modules/module2/index.ts`); + const { module1, module2 } = getModules(`${projectRoot}/product/node_modules/module1/index.ts`, `${projectRoot}/node_modules/module2/index.ts`); const files = [module1, module2, file1, file2, file3, file4, libFile]; const host = createServerHost(files); const resolutionTrace = createHostModuleResolutionTrace(host); @@ -811,19 +766,19 @@ namespace ts.projectSystem { getExpectedNonRelativeModuleResolutionTrace(host, file1, module2, module2Name, expectedTrace); getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file2, module1, module1Name, getDirectoryPath(file1.path), expectedTrace); getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file2, module2, module2Name, getDirectoryPath(file1.path), expectedTrace); - getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file4, module1, module1Name, `${projectLocation}/product`, expectedTrace); - getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file4, module2, module2Name, `${projectLocation}/product`, expectedTrace); + getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file4, module1, module1Name, `${projectRoot}/product`, expectedTrace); + getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file4, module2, module2Name, `${projectRoot}/product`, expectedTrace); getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file3, module1, module1Name, getDirectoryPath(file4.path), expectedTrace); getExpectedNonRelativeModuleResolutionFromCacheTrace(host, file3, module2, module2Name, getDirectoryPath(file4.path), expectedTrace); verifyTrace(resolutionTrace, expectedTrace); const currentDirectory = getDirectoryPath(file1.path); const watchedFiles = mapDefined(files, f => f === file1 || f.path.indexOf("/node_modules/") !== -1 ? undefined : f.path) - .concat(getConfigFilesToWatch(`${projectLocation}/product/src`)); + .concat(getConfigFilesToWatch(`${projectRoot}/product/src`)); const watchedRecursiveDirectories = getTypeRootsFromLocation(currentDirectory).concat([ - `${currentDirectory}/node_modules`, `${currentDirectory}/feature`, `${projectLocation}/product/${nodeModules}`, - `${projectLocation}/${nodeModules}`, `${projectLocation}/product/test/${nodeModules}`, - `${projectLocation}/product/test/src/${nodeModules}` + `${currentDirectory}/node_modules`, `${currentDirectory}/feature`, `${projectRoot}/product/${nodeModules}`, + `${projectRoot}/${nodeModules}`, `${projectRoot}/product/test/${nodeModules}`, + `${projectRoot}/product/test/src/${nodeModules}` ]); checkWatches(); @@ -852,7 +807,6 @@ namespace ts.projectSystem { }); describe("when watching directories for failed lookup locations in amd resolution", () => { - const projectRoot = "/user/username/projects/project"; const nodeFile: File = { path: `${projectRoot}/src/typings/node.d.ts`, content: ` @@ -928,17 +882,16 @@ export const x = 10;` }); describe("ignores files/folder changes in node_modules that start with '.'", () => { - const projectPath = "/user/username/projects/project"; const npmCacheFile: File = { - path: `${projectPath}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`, + path: `${projectRoot}/node_modules/.cache/babel-loader/89c02171edab901b9926470ba6d5677e.ts`, content: JSON.stringify({ something: 10 }) }; const file1: File = { - path: `${projectPath}/test.ts`, + path: `${projectRoot}/test.ts`, content: `import { x } from "somemodule";` }; const file2: File = { - path: `${projectPath}/node_modules/somemodule/index.d.ts`, + path: `${projectRoot}/node_modules/somemodule/index.d.ts`, content: `export const x = 10;` }; it("when watching node_modules in inferred project for failed lookup/closed script infos", () => { @@ -957,7 +910,7 @@ export const x = 10;` }); it("when watching node_modules as part of wild card directories in config project", () => { const config: File = { - path: `${projectPath}/tsconfig.json`, + path: `${projectRoot}/tsconfig.json`, content: "{}" }; const files = [libFile, file1, file2, config]; @@ -976,15 +929,15 @@ export const x = 10;` describe("avoid unnecessary invalidation", () => { it("unnecessary lookup invalidation on save", () => { - const expectedNonRelativeDirectories = [`${projectLocation}/node_modules`, `${projectLocation}/src`]; + const expectedNonRelativeDirectories = [`${projectRoot}/node_modules`, `${projectRoot}/src`]; const module1Name = "module1"; const module2Name = "module2"; const fileContent = `import { module1 } from "${module1Name}";import { module2 } from "${module2Name}";`; const file1: File = { - path: `${projectLocation}/src/file1.ts`, + path: `${projectRoot}/src/file1.ts`, content: fileContent }; - const { module1, module2 } = getModules(`${projectLocation}/src/node_modules/module1/index.ts`, `${projectLocation}/node_modules/module2/index.ts`); + const { module1, module2 } = getModules(`${projectRoot}/src/node_modules/module1/index.ts`, `${projectRoot}/node_modules/module2/index.ts`); const files = [module1, module2, file1, configFile, libFile]; const host = createServerHost(files); const resolutionTrace = createHostModuleResolutionTrace(host); diff --git a/src/testRunner/unittests/tsserver/symLinks.ts b/src/testRunner/unittests/tsserver/symLinks.ts index 54b7cb3fab4..4576dc90c07 100644 --- a/src/testRunner/unittests/tsserver/symLinks.ts +++ b/src/testRunner/unittests/tsserver/symLinks.ts @@ -149,34 +149,16 @@ new C();` const filesInProjectWithResolvedModule = [...filesInProjectWithUnresolvedModule, recongnizerTextDistTypingFile.path]; function verifyErrors(session: TestSession, semanticErrors: protocol.Diagnostic[]) { - session.clearMessages(); - const expectedSequenceId = session.getNextSeq(); - session.executeCommandSeq({ - command: server.CommandNames.Geterr, - arguments: { - delay: 0, - files: [recognizersDateTimeSrcFile.path], - } + verifyGetErrRequest({ + session, + host: session.testhost, + expected: [{ + file: recognizersDateTimeSrcFile, + syntax: [], + semantic: semanticErrors, + suggestion: [] + }] }); - - const host = session.testhost; - host.checkTimeoutQueueLengthAndRun(1); - - checkErrorMessage(session, "syntaxDiag", { file: recognizersDateTimeSrcFile.path, diagnostics: [] }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - - checkErrorMessage(session, "semanticDiag", { file: recognizersDateTimeSrcFile.path, diagnostics: semanticErrors }); - session.clearMessages(); - - host.runQueuedImmediateCallbacks(1); - - checkErrorMessage(session, "suggestionDiag", { - file: recognizersDateTimeSrcFile.path, - diagnostics: [], - }); - checkCompleteEvent(session, 2, expectedSequenceId); } function verifyWatchedFilesAndDirectories(host: TestServerHost, files: string[], recursiveDirectories: ReadonlyMap, nonRecursiveDirectories: string[]) { diff --git a/src/testRunner/unittests/tsserver/syntaxOperations.ts b/src/testRunner/unittests/tsserver/syntaxOperations.ts index d3127355191..ec5610b649e 100644 --- a/src/testRunner/unittests/tsserver/syntaxOperations.ts +++ b/src/testRunner/unittests/tsserver/syntaxOperations.ts @@ -15,7 +15,6 @@ namespace ts.projectSystem { } it("works when file is removed and added with different content", () => { - const projectRoot = "/user/username/projects/myproject"; const app: File = { path: `${projectRoot}/app.ts`, content: "console.log('Hello world');" diff --git a/src/testRunner/unittests/tsserver/typeReferenceDirectives.ts b/src/testRunner/unittests/tsserver/typeReferenceDirectives.ts index e3ad121e427..42f97733985 100644 --- a/src/testRunner/unittests/tsserver/typeReferenceDirectives.ts +++ b/src/testRunner/unittests/tsserver/typeReferenceDirectives.ts @@ -1,8 +1,7 @@ namespace ts.projectSystem { describe("unittests:: tsserver:: typeReferenceDirectives", () => { it("when typeReferenceDirective contains UpperCasePackage", () => { - const projectLocation = "/user/username/projects/myproject"; - const libProjectLocation = `${projectLocation}/lib`; + const libProjectLocation = `${projectRoot}/lib`; const typeLib: File = { path: `${libProjectLocation}/@types/UpperCasePackage/index.d.ts`, content: `declare class BrokenTest { @@ -20,7 +19,7 @@ declare class TestLib { test(): void; }` }; - const testProjectLocation = `${projectLocation}/test`; + const testProjectLocation = `${projectRoot}/test`; const testFile: File = { path: `${testProjectLocation}/test.ts`, content: `class TestClass1 { @@ -58,8 +57,7 @@ declare class TestLib { }); it("when typeReferenceDirective is relative path and in a sibling folder", () => { - const projectRootPath = "/user/username/projects/browser-addon"; - const projectPath = `${projectRootPath}/background`; + const projectPath = `${projectRoot}/background`; const file: File = { path: `${projectPath}/a.ts`, content: "let x = 10;" @@ -75,7 +73,7 @@ declare class TestLib { }) }; const filesystem: File = { - path: `${projectRootPath}/typedefs/filesystem.d.ts`, + path: `${projectRoot}/typedefs/filesystem.d.ts`, content: `interface LocalFileSystem { someProperty: string; }` }; const files = [file, tsconfig, filesystem, libFile]; diff --git a/src/testRunner/unittests/tsserver/typingsInstaller.ts b/src/testRunner/unittests/tsserver/typingsInstaller.ts index 1b7f156057d..cecc6c4383a 100644 --- a/src/testRunner/unittests/tsserver/typingsInstaller.ts +++ b/src/testRunner/unittests/tsserver/typingsInstaller.ts @@ -994,7 +994,6 @@ namespace ts.projectSystem { }); it("should redo resolution that resolved to '.js' file after typings are installed", () => { - const projects = `/user/username/projects`; const file: TestFSWithWatch.File = { path: `${projects}/a/b/app.js`, content: ` diff --git a/src/tsc/executeCommandLine.ts b/src/tsc/executeCommandLine.ts new file mode 100644 index 00000000000..d730de4a981 --- /dev/null +++ b/src/tsc/executeCommandLine.ts @@ -0,0 +1,729 @@ +namespace ts { + interface Statistic { + name: string; + value: string; + } + + function countLines(program: Program): number { + let count = 0; + forEach(program.getSourceFiles(), file => { + count += getLineStarts(file).length; + }); + return count; + } + + function updateReportDiagnostic( + sys: System, + existing: DiagnosticReporter, + options: CompilerOptions | BuildOptions + ): DiagnosticReporter { + return shouldBePretty(sys, options) ? + createDiagnosticReporter(sys, /*pretty*/ true) : + existing; + } + + function defaultIsPretty(sys: System) { + return !!sys.writeOutputIsTTY && sys.writeOutputIsTTY(); + } + + function shouldBePretty(sys: System, options: CompilerOptions | BuildOptions) { + if (!options || typeof options.pretty === "undefined") { + return defaultIsPretty(sys); + } + return options.pretty; + } + + function padLeft(s: string, length: number) { + while (s.length < length) { + s = " " + s; + } + return s; + } + + function padRight(s: string, length: number) { + while (s.length < length) { + s = s + " "; + } + + return s; + } + + function getOptionsForHelp(commandLine: ParsedCommandLine) { + // Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch") + return !!commandLine.options.all ? + sort(optionDeclarations, (a, b) => compareStringsCaseInsensitive(a.name, b.name)) : + filter(optionDeclarations.slice(), v => !!v.showInSimplifiedHelpView); + } + + function printVersion(sys: System) { + sys.write(getDiagnosticText(Diagnostics.Version_0, version) + sys.newLine); + } + + function printHelp(sys: System, optionsList: readonly CommandLineOption[], syntaxPrefix = "") { + const output: string[] = []; + + // We want to align our "syntax" and "examples" commands to a certain margin. + const syntaxLength = getDiagnosticText(Diagnostics.Syntax_Colon_0, "").length; + const examplesLength = getDiagnosticText(Diagnostics.Examples_Colon_0, "").length; + let marginLength = Math.max(syntaxLength, examplesLength); + + // Build up the syntactic skeleton. + let syntax = makePadding(marginLength - syntaxLength); + syntax += `tsc ${syntaxPrefix}[${getDiagnosticText(Diagnostics.options)}] [${getDiagnosticText(Diagnostics.file)}...]`; + + output.push(getDiagnosticText(Diagnostics.Syntax_Colon_0, syntax)); + output.push(sys.newLine + sys.newLine); + + // Build up the list of examples. + const padding = makePadding(marginLength); + output.push(getDiagnosticText(Diagnostics.Examples_Colon_0, makePadding(marginLength - examplesLength) + "tsc hello.ts") + sys.newLine); + output.push(padding + "tsc --outFile file.js file.ts" + sys.newLine); + output.push(padding + "tsc @args.txt" + sys.newLine); + output.push(padding + "tsc --build tsconfig.json" + sys.newLine); + output.push(sys.newLine); + + output.push(getDiagnosticText(Diagnostics.Options_Colon) + sys.newLine); + + // We want our descriptions to align at the same column in our output, + // so we keep track of the longest option usage string. + marginLength = 0; + const usageColumn: string[] = []; // Things like "-d, --declaration" go in here. + const descriptionColumn: string[] = []; + + const optionsDescriptionMap = createMap(); // Map between option.description and list of option.type if it is a kind + + for (const option of optionsList) { + // If an option lacks a description, + // it is not officially supported. + if (!option.description) { + continue; + } + + let usageText = " "; + if (option.shortName) { + usageText += "-" + option.shortName; + usageText += getParamType(option); + usageText += ", "; + } + + usageText += "--" + option.name; + usageText += getParamType(option); + + usageColumn.push(usageText); + let description: string; + + if (option.name === "lib") { + description = getDiagnosticText(option.description); + const element = (option).element; + const typeMap = >element.type; + optionsDescriptionMap.set(description, arrayFrom(typeMap.keys()).map(key => `'${key}'`)); + } + else { + description = getDiagnosticText(option.description); + } + + descriptionColumn.push(description); + + // Set the new margin for the description column if necessary. + marginLength = Math.max(usageText.length, marginLength); + } + + // Special case that can't fit in the loop. + const usageText = " @<" + getDiagnosticText(Diagnostics.file) + ">"; + usageColumn.push(usageText); + descriptionColumn.push(getDiagnosticText(Diagnostics.Insert_command_line_options_and_files_from_a_file)); + marginLength = Math.max(usageText.length, marginLength); + + // Print out each row, aligning all the descriptions on the same column. + for (let i = 0; i < usageColumn.length; i++) { + const usage = usageColumn[i]; + const description = descriptionColumn[i]; + const kindsList = optionsDescriptionMap.get(description); + output.push(usage + makePadding(marginLength - usage.length + 2) + description + sys.newLine); + + if (kindsList) { + output.push(makePadding(marginLength + 4)); + for (const kind of kindsList) { + output.push(kind + " "); + } + output.push(sys.newLine); + } + } + + for (const line of output) { + sys.write(line); + } + return; + + function getParamType(option: CommandLineOption) { + if (option.paramType !== undefined) { + return " " + getDiagnosticText(option.paramType); + } + return ""; + } + + function makePadding(paddingLength: number): string { + return Array(paddingLength + 1).join(" "); + } + } + + function executeCommandLineWorker( + sys: System, + cb: ExecuteCommandLineCallbacks | undefined, + commandLine: ParsedCommandLine, + ) { + let reportDiagnostic = createDiagnosticReporter(sys); + if (commandLine.options.build) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_build_must_be_the_first_command_line_argument)); + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + + // Configuration file name (if any) + let configFileName: string | undefined; + if (commandLine.options.locale) { + validateLocaleAndSetLanguage(commandLine.options.locale, sys, commandLine.errors); + } + + // If there are any errors due to command line parsing and/or + // setting up localization, report them and quit. + if (commandLine.errors.length > 0) { + commandLine.errors.forEach(reportDiagnostic); + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + + if (commandLine.options.init) { + writeConfigFile(sys, reportDiagnostic, commandLine.options, commandLine.fileNames); + return sys.exit(ExitStatus.Success); + } + + if (commandLine.options.version) { + printVersion(sys); + return sys.exit(ExitStatus.Success); + } + + if (commandLine.options.help || commandLine.options.all) { + printVersion(sys); + printHelp(sys, getOptionsForHelp(commandLine)); + return sys.exit(ExitStatus.Success); + } + + if (commandLine.options.watch && commandLine.options.listFilesOnly) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "listFilesOnly")); + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + + if (commandLine.options.project) { + if (commandLine.fileNames.length !== 0) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line)); + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + + const fileOrDirectory = normalizePath(commandLine.options.project); + if (!fileOrDirectory /* current directory "." */ || sys.directoryExists(fileOrDirectory)) { + configFileName = combinePaths(fileOrDirectory, "tsconfig.json"); + if (!sys.fileExists(configFileName)) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project)); + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } + else { + configFileName = fileOrDirectory; + if (!sys.fileExists(configFileName)) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project)); + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + } + } + else if (commandLine.fileNames.length === 0) { + const searchPath = normalizePath(sys.getCurrentDirectory()); + configFileName = findConfigFile(searchPath, sys.fileExists); + } + + if (commandLine.fileNames.length === 0 && !configFileName) { + printVersion(sys); + printHelp(sys, getOptionsForHelp(commandLine)); + return sys.exit(ExitStatus.Success); + } + + const currentDirectory = sys.getCurrentDirectory(); + const commandLineOptions = convertToOptionsWithAbsolutePaths( + commandLine.options, + fileName => getNormalizedAbsolutePath(fileName, currentDirectory) + ); + if (configFileName) { + const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, sys, reportDiagnostic)!; // TODO: GH#18217 + if (commandLineOptions.showConfig) { + if (configParseResult.errors.length !== 0) { + reportDiagnostic = updateReportDiagnostic( + sys, + reportDiagnostic, + configParseResult.options + ); + configParseResult.errors.forEach(reportDiagnostic); + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + // eslint-disable-next-line no-null/no-null + sys.write(JSON.stringify(convertToTSConfig(configParseResult, configFileName, sys), null, 4) + sys.newLine); + return sys.exit(ExitStatus.Success); + } + reportDiagnostic = updateReportDiagnostic( + sys, + reportDiagnostic, + configParseResult.options + ); + if (isWatchSet(configParseResult.options)) { + if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) return; + createWatchOfConfigFile( + sys, + reportDiagnostic, + configParseResult, + commandLineOptions + ); + } + else if (isIncrementalCompilation(configParseResult.options)) { + performIncrementalCompilation( + sys, + reportDiagnostic, + cb, + configParseResult + ); + } + else { + performCompilation( + sys, + reportDiagnostic, + cb, + configParseResult + ); + } + } + else { + if (commandLineOptions.showConfig) { + // eslint-disable-next-line no-null/no-null + sys.write(JSON.stringify(convertToTSConfig(commandLine, combinePaths(currentDirectory, "tsconfig.json"), sys), null, 4) + sys.newLine); + return sys.exit(ExitStatus.Success); + } + reportDiagnostic = updateReportDiagnostic( + sys, + reportDiagnostic, + commandLineOptions + ); + if (isWatchSet(commandLineOptions)) { + if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) return; + createWatchOfFilesAndCompilerOptions( + sys, + reportDiagnostic, + commandLine.fileNames, + commandLineOptions + ); + } + else if (isIncrementalCompilation(commandLineOptions)) { + performIncrementalCompilation( + sys, + reportDiagnostic, + cb, + { ...commandLine, options: commandLineOptions } + ); + } + else { + performCompilation( + sys, + reportDiagnostic, + cb, + { ...commandLine, options: commandLineOptions } + ); + } + } + } + + export function isBuild(commandLineArgs: readonly string[]) { + if (commandLineArgs.length > 0 && commandLineArgs[0].charCodeAt(0) === CharacterCodes.minus) { + const firstOption = commandLineArgs[0].slice(commandLineArgs[0].charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase(); + return firstOption === "build" || firstOption === "b"; + } + return false; + } + + export interface ExecuteCommandLineCallbacks { + onCompilerHostCreate: (host: CompilerHost) => void; + onCompilationComplete: (config: ParsedCommandLine) => void; + onSolutionBuilderHostCreate: (host: SolutionBuilderHost | SolutionBuilderWithWatchHost) => void; + onSolutionBuildComplete: (configs: readonly ParsedCommandLine[]) => void; + } + export function executeCommandLine( + system: System, + cb: ExecuteCommandLineCallbacks, + commandLineArgs: readonly string[], + ): void { + if (isBuild(commandLineArgs)) { + return performBuild( + system, + cb, + commandLineArgs.slice(1) + ); + } + + const commandLine = parseCommandLine(commandLineArgs, path => system.readFile(path)); + if (commandLine.options.generateCpuProfile && system.enableCPUProfiler) { + system.enableCPUProfiler(commandLine.options.generateCpuProfile, () => executeCommandLineWorker( + system, + cb, + commandLine + )); + } + else { + executeCommandLineWorker(system, cb, commandLine); + } + } + + function reportWatchModeWithoutSysSupport(sys: System, reportDiagnostic: DiagnosticReporter) { + if (!sys.watchFile || !sys.watchDirectory) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); + sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + return true; + } + return false; + } + + function performBuildWorker( + sys: System, + cb: ExecuteCommandLineCallbacks | undefined, + buildOptions: BuildOptions, + projects: string[], + errors: Diagnostic[] + ) { + // Update to pretty if host supports it + const reportDiagnostic = updateReportDiagnostic( + sys, + createDiagnosticReporter(sys), + buildOptions + ); + + if (buildOptions.locale) { + validateLocaleAndSetLanguage(buildOptions.locale, sys, errors); + } + + if (errors.length > 0) { + errors.forEach(reportDiagnostic); + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + + if (buildOptions.help) { + printVersion(sys); + printHelp(sys, buildOpts, "--build "); + return sys.exit(ExitStatus.Success); + } + + if (projects.length === 0) { + printVersion(sys); + printHelp(sys, buildOpts, "--build "); + return sys.exit(ExitStatus.Success); + } + + if (!sys.getModifiedTime || !sys.setModifiedTime || (buildOptions.clean && !sys.deleteFile)) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); + return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); + } + + if (buildOptions.watch) { + if (reportWatchModeWithoutSysSupport(sys, reportDiagnostic)) return; + const buildHost = createSolutionBuilderWithWatchHost( + sys, + /*createProgram*/ undefined, + reportDiagnostic, + createBuilderStatusReporter(sys, shouldBePretty(sys, buildOptions)), + createWatchStatusReporter(sys, buildOptions) + ); + if (cb && cb.onSolutionBuilderHostCreate) cb.onSolutionBuilderHostCreate(buildHost); + updateCreateProgram(sys, buildHost); + buildHost.afterProgramEmitAndDiagnostics = program => reportStatistics(sys, program.getProgram()); + const builder = createSolutionBuilderWithWatch(buildHost, projects, buildOptions); + builder.build(); + return; + } + + const buildHost = createSolutionBuilderHost( + sys, + /*createProgram*/ undefined, + reportDiagnostic, + createBuilderStatusReporter(sys, shouldBePretty(sys, buildOptions)), + createReportErrorSummary(sys, buildOptions) + ); + if (cb && cb.onSolutionBuilderHostCreate) cb.onSolutionBuilderHostCreate(buildHost); + updateCreateProgram(sys, buildHost); + buildHost.afterProgramEmitAndDiagnostics = program => reportStatistics(sys, program.getProgram()); + const builder = createSolutionBuilder(buildHost, projects, buildOptions); + const exitStatus = buildOptions.clean ? builder.clean() : builder.build(); + if (cb && cb.onSolutionBuildComplete) cb.onSolutionBuildComplete(builder.getAllParsedConfigs()); + return sys.exit(exitStatus); + } + + function performBuild( + sys: System, + cb: ExecuteCommandLineCallbacks | undefined, + args: readonly string[] + ) { + const { buildOptions, projects, errors } = parseBuildCommand(args); + if (buildOptions.generateCpuProfile && sys.enableCPUProfiler) { + sys.enableCPUProfiler(buildOptions.generateCpuProfile, () => performBuildWorker( + sys, + cb, + buildOptions, + projects, + errors + )); + } + else { + performBuildWorker( + sys, + cb, + buildOptions, + projects, + errors + ); + } + } + + function createReportErrorSummary(sys: System, options: CompilerOptions | BuildOptions): ReportEmitErrorSummary | undefined { + return shouldBePretty(sys, options) ? + errorCount => sys.write(getErrorSummaryText(errorCount, sys.newLine)) : + undefined; + } + + function performCompilation( + sys: System, + reportDiagnostic: DiagnosticReporter, + cb: ExecuteCommandLineCallbacks | undefined, + config: ParsedCommandLine + ) { + const { fileNames, options, projectReferences } = config; + const host = createCompilerHostWorker(options, /*setParentPos*/ undefined, sys); + if (cb && cb.onCompilerHostCreate) cb.onCompilerHostCreate(host); + const currentDirectory = host.getCurrentDirectory(); + const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); + changeCompilerHostLikeToUseCache(host, fileName => toPath(fileName, currentDirectory, getCanonicalFileName)); + enableStatistics(sys, options); + + const programOptions: CreateProgramOptions = { + rootNames: fileNames, + options, + projectReferences, + host, + configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config) + }; + const program = createProgram(programOptions); + const exitStatus = emitFilesAndReportErrorsAndGetExitStatus( + program, + reportDiagnostic, + s => sys.write(s + sys.newLine), + createReportErrorSummary(sys, options) + ); + reportStatistics(sys, program); + if (cb && cb.onCompilationComplete) cb.onCompilationComplete(config); + return sys.exit(exitStatus); + } + + function performIncrementalCompilation( + sys: System, + reportDiagnostic: DiagnosticReporter, + cb: ExecuteCommandLineCallbacks | undefined, + config: ParsedCommandLine + ) { + const { options, fileNames, projectReferences } = config; + enableStatistics(sys, options); + const host = createIncrementalCompilerHost(options, sys); + if (cb && cb.onCompilerHostCreate) cb.onCompilerHostCreate(host); + const exitStatus = ts.performIncrementalCompilation({ + host, + system: sys, + rootNames: fileNames, + options, + configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config), + projectReferences, + reportDiagnostic, + reportErrorSummary: createReportErrorSummary(sys, options), + afterProgramEmitAndDiagnostics: builderProgram => reportStatistics(sys, builderProgram.getProgram()) + }); + if (cb && cb.onCompilationComplete) cb.onCompilationComplete(config); + return sys.exit(exitStatus); + } + + function updateCreateProgram(sys: System, host: { createProgram: CreateProgram; }) { + const compileUsingBuilder = host.createProgram; + host.createProgram = (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) => { + Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); + if (options !== undefined) { + enableStatistics(sys, options); + } + return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); + }; + } + + function updateWatchCompilationHost(sys: System, watchCompilerHost: WatchCompilerHost) { + updateCreateProgram(sys, watchCompilerHost); + const emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate!; // TODO: GH#18217 + watchCompilerHost.afterProgramCreate = builderProgram => { + emitFilesUsingBuilder(builderProgram); + reportStatistics(sys, builderProgram.getProgram()); + }; + } + + function createWatchStatusReporter(sys: System, options: CompilerOptions | BuildOptions) { + return ts.createWatchStatusReporter(sys, shouldBePretty(sys, options)); + } + + function createWatchOfConfigFile( + sys: System, + reportDiagnostic: DiagnosticReporter, + configParseResult: ParsedCommandLine, + optionsToExtend: CompilerOptions + ) { + const watchCompilerHost = createWatchCompilerHostOfConfigFile( + configParseResult.options.configFilePath!, + optionsToExtend, + sys, + /*createProgram*/ undefined, + reportDiagnostic, + createWatchStatusReporter(sys, configParseResult.options) + ); // TODO: GH#18217 + updateWatchCompilationHost(sys, watchCompilerHost); + watchCompilerHost.configFileParsingResult = configParseResult; + createWatchProgram(watchCompilerHost); + } + + function createWatchOfFilesAndCompilerOptions( + sys: System, + reportDiagnostic: DiagnosticReporter, + rootFiles: string[], + options: CompilerOptions + ) { + const watchCompilerHost = createWatchCompilerHostOfFilesAndCompilerOptions( + rootFiles, + options, + sys, + /*createProgram*/ undefined, + reportDiagnostic, + createWatchStatusReporter(sys, options) + ); + updateWatchCompilationHost(sys, watchCompilerHost); + createWatchProgram(watchCompilerHost); + } + + function canReportDiagnostics(system: System, compilerOptions: CompilerOptions) { + return system === sys && (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics); + } + + function enableStatistics(sys: System, compilerOptions: CompilerOptions) { + if (canReportDiagnostics(sys, compilerOptions)) { + performance.enable(); + } + } + + function reportStatistics(sys: System, program: Program) { + let statistics: Statistic[]; + const compilerOptions = program.getCompilerOptions(); + if (canReportDiagnostics(sys, compilerOptions)) { + statistics = []; + const memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; + reportCountStatistic("Files", program.getSourceFiles().length); + reportCountStatistic("Lines", countLines(program)); + reportCountStatistic("Nodes", program.getNodeCount()); + reportCountStatistic("Identifiers", program.getIdentifierCount()); + reportCountStatistic("Symbols", program.getSymbolCount()); + reportCountStatistic("Types", program.getTypeCount()); + + if (memoryUsed >= 0) { + reportStatisticalValue("Memory used", Math.round(memoryUsed / 1000) + "K"); + } + + const programTime = performance.getDuration("Program"); + const bindTime = performance.getDuration("Bind"); + const checkTime = performance.getDuration("Check"); + const emitTime = performance.getDuration("Emit"); + if (compilerOptions.extendedDiagnostics) { + const caches = program.getRelationCacheSizes(); + reportCountStatistic("Assignability cache size", caches.assignable); + reportCountStatistic("Identity cache size", caches.identity); + reportCountStatistic("Subtype cache size", caches.subtype); + performance.forEachMeasure((name, duration) => reportTimeStatistic(`${name} time`, duration)); + } + else { + // Individual component times. + // Note: To match the behavior of previous versions of the compiler, the reported parse time includes + // I/O read time and processing time for triple-slash references and module imports, and the reported + // emit time includes I/O write time. We preserve this behavior so we can accurately compare times. + reportTimeStatistic("I/O read", performance.getDuration("I/O Read")); + reportTimeStatistic("I/O write", performance.getDuration("I/O Write")); + reportTimeStatistic("Parse time", programTime); + reportTimeStatistic("Bind time", bindTime); + reportTimeStatistic("Check time", checkTime); + reportTimeStatistic("Emit time", emitTime); + } + reportTimeStatistic("Total time", programTime + bindTime + checkTime + emitTime); + reportStatistics(); + + performance.disable(); + } + + function reportStatistics() { + let nameSize = 0; + let valueSize = 0; + for (const { name, value } of statistics) { + if (name.length > nameSize) { + nameSize = name.length; + } + + if (value.length > valueSize) { + valueSize = value.length; + } + } + + for (const { name, value } of statistics) { + sys.write(padRight(name + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + sys.newLine); + } + } + + function reportStatisticalValue(name: string, value: string) { + statistics.push({ name, value }); + } + + function reportCountStatistic(name: string, count: number) { + reportStatisticalValue(name, "" + count); + } + + function reportTimeStatistic(name: string, time: number) { + reportStatisticalValue(name, (time / 1000).toFixed(2) + "s"); + } + } + + function writeConfigFile( + sys: System, + reportDiagnostic: DiagnosticReporter, + options: CompilerOptions, + fileNames: string[] + ) { + const currentDirectory = sys.getCurrentDirectory(); + const file = normalizePath(combinePaths(currentDirectory, "tsconfig.json")); + if (sys.fileExists(file)) { + reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file)); + } + else { + sys.writeFile(file, generateTSConfig(options, fileNames, sys.newLine)); + reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file)); + } + + return; + } +} + +if (ts.Debug.isDebugging) { + ts.Debug.enableDebugInfo(); +} + +if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) { + ts.sys.tryEnableSourceMapsForHost(); +} + +if (ts.sys.setBlocking) { + ts.sys.setBlocking(); +} diff --git a/src/tsc/tsc.ts b/src/tsc/tsc.ts index b6388528223..17c45fbf0d0 100644 --- a/src/tsc/tsc.ts +++ b/src/tsc/tsc.ts @@ -1,442 +1,11 @@ -namespace ts { - interface Statistic { - name: string; - value: string; - } - - function countLines(program: Program): number { - let count = 0; - forEach(program.getSourceFiles(), file => { - count += getLineStarts(file).length; - }); - return count; - } - - let reportDiagnostic = createDiagnosticReporter(sys); - function updateReportDiagnostic(options: CompilerOptions | BuildOptions) { - if (shouldBePretty(options)) { - reportDiagnostic = createDiagnosticReporter(sys, /*pretty*/ true); - } - } - - function defaultIsPretty() { - return !!sys.writeOutputIsTTY && sys.writeOutputIsTTY(); - } - - function shouldBePretty(options: CompilerOptions | BuildOptions) { - if (!options || typeof options.pretty === "undefined") { - return defaultIsPretty(); - } - return options.pretty; - } - - function padLeft(s: string, length: number) { - while (s.length < length) { - s = " " + s; - } - return s; - } - - function padRight(s: string, length: number) { - while (s.length < length) { - s = s + " "; - } - - return s; - } - - function getOptionsForHelp(commandLine: ParsedCommandLine) { - // Sort our options by their names, (e.g. "--noImplicitAny" comes before "--watch") - return !!commandLine.options.all ? - sort(optionDeclarations, (a, b) => compareStringsCaseInsensitive(a.name, b.name)) : - filter(optionDeclarations.slice(), v => !!v.showInSimplifiedHelpView); - } - - function executeCommandLineWorker(commandLine: ParsedCommandLine) { - if (commandLine.options.build) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_build_must_be_the_first_command_line_argument)); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - - // Configuration file name (if any) - let configFileName: string | undefined; - if (commandLine.options.locale) { - validateLocaleAndSetLanguage(commandLine.options.locale, sys, commandLine.errors); - } - - // If there are any errors due to command line parsing and/or - // setting up localization, report them and quit. - if (commandLine.errors.length > 0) { - commandLine.errors.forEach(reportDiagnostic); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - - if (commandLine.options.init) { - writeConfigFile(commandLine.options, commandLine.fileNames); - return sys.exit(ExitStatus.Success); - } - - if (commandLine.options.version) { - printVersion(); - return sys.exit(ExitStatus.Success); - } - - if (commandLine.options.help || commandLine.options.all) { - printVersion(); - printHelp(getOptionsForHelp(commandLine)); - return sys.exit(ExitStatus.Success); - } - - if (commandLine.options.project) { - if (commandLine.fileNames.length !== 0) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Option_project_cannot_be_mixed_with_source_files_on_a_command_line)); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - - const fileOrDirectory = normalizePath(commandLine.options.project); - if (!fileOrDirectory /* current directory "." */ || sys.directoryExists(fileOrDirectory)) { - configFileName = combinePaths(fileOrDirectory, "tsconfig.json"); - if (!sys.fileExists(configFileName)) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Cannot_find_a_tsconfig_json_file_at_the_specified_directory_Colon_0, commandLine.options.project)); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - } - else { - configFileName = fileOrDirectory; - if (!sys.fileExists(configFileName)) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_specified_path_does_not_exist_Colon_0, commandLine.options.project)); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - } - } - else if (commandLine.fileNames.length === 0) { - const searchPath = normalizePath(sys.getCurrentDirectory()); - configFileName = findConfigFile(searchPath, sys.fileExists); - } - - if (commandLine.fileNames.length === 0 && !configFileName) { - printVersion(); - printHelp(getOptionsForHelp(commandLine)); - return sys.exit(ExitStatus.Success); - } - - const commandLineOptions = commandLine.options; - if (configFileName) { - const configParseResult = parseConfigFileWithSystem(configFileName, commandLineOptions, sys, reportDiagnostic)!; // TODO: GH#18217 - if (commandLineOptions.showConfig) { - if (configParseResult.errors.length !== 0) { - updateReportDiagnostic(configParseResult.options); - configParseResult.errors.forEach(reportDiagnostic); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - // eslint-disable-next-line no-null/no-null - sys.write(JSON.stringify(convertToTSConfig(configParseResult, configFileName, sys), null, 4) + sys.newLine); - return sys.exit(ExitStatus.Success); - } - updateReportDiagnostic(configParseResult.options); - if (isWatchSet(configParseResult.options)) { - reportWatchModeWithoutSysSupport(); - createWatchOfConfigFile(configParseResult, commandLineOptions); - } - else if (isIncrementalCompilation(configParseResult.options)) { - performIncrementalCompilation(configParseResult); - } - else { - performCompilation(configParseResult.fileNames, configParseResult.projectReferences, configParseResult.options, getConfigFileParsingDiagnostics(configParseResult)); - } - } - else { - if (commandLineOptions.showConfig) { - // eslint-disable-next-line no-null/no-null - sys.write(JSON.stringify(convertToTSConfig(commandLine, combinePaths(sys.getCurrentDirectory(), "tsconfig.json"), sys), null, 4) + sys.newLine); - return sys.exit(ExitStatus.Success); - } - updateReportDiagnostic(commandLineOptions); - if (isWatchSet(commandLineOptions)) { - reportWatchModeWithoutSysSupport(); - createWatchOfFilesAndCompilerOptions(commandLine.fileNames, commandLineOptions); - } - else if (isIncrementalCompilation(commandLineOptions)) { - performIncrementalCompilation(commandLine); - } - else { - performCompilation(commandLine.fileNames, /*references*/ undefined, commandLineOptions); - } - } - } - - export function executeCommandLine(args: string[]): void { - if (args.length > 0 && args[0].charCodeAt(0) === CharacterCodes.minus) { - const firstOption = args[0].slice(args[0].charCodeAt(1) === CharacterCodes.minus ? 2 : 1).toLowerCase(); - if (firstOption === "build" || firstOption === "b") { - return performBuild(args.slice(1)); - } - } - - const commandLine = parseCommandLine(args); - - if (commandLine.options.generateCpuProfile && sys.enableCPUProfiler) { - sys.enableCPUProfiler(commandLine.options.generateCpuProfile, () => executeCommandLineWorker(commandLine)); - } - else { - executeCommandLineWorker(commandLine); - } - } - - function reportWatchModeWithoutSysSupport() { - if (!sys.watchFile || !sys.watchDirectory) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--watch")); - sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - } - - function performBuildWorker(buildOptions: BuildOptions, projects: string[], errors: Diagnostic[]) { - // Update to pretty if host supports it - updateReportDiagnostic(buildOptions); - - if (buildOptions.locale) { - validateLocaleAndSetLanguage(buildOptions.locale, sys, errors); - } - - if (errors.length > 0) { - errors.forEach(reportDiagnostic); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - - if (buildOptions.help) { - printVersion(); - printHelp(buildOpts, "--build "); - return sys.exit(ExitStatus.Success); - } - - if (projects.length === 0) { - printVersion(); - printHelp(buildOpts, "--build "); - return sys.exit(ExitStatus.Success); - } - - if (!sys.getModifiedTime || !sys.setModifiedTime || (buildOptions.clean && !sys.deleteFile)) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.The_current_host_does_not_support_the_0_option, "--build")); - return sys.exit(ExitStatus.DiagnosticsPresent_OutputsSkipped); - } - - if (buildOptions.watch) { - reportWatchModeWithoutSysSupport(); - const buildHost = createSolutionBuilderWithWatchHost(sys, /*createProgram*/ undefined, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty(buildOptions)), createWatchStatusReporter(buildOptions)); - updateCreateProgram(buildHost); - buildHost.afterProgramEmitAndDiagnostics = program => reportStatistics(program.getProgram()); - const builder = createSolutionBuilderWithWatch(buildHost, projects, buildOptions); - builder.build(); - return; - } - - const buildHost = createSolutionBuilderHost(sys, /*createProgram*/ undefined, reportDiagnostic, createBuilderStatusReporter(sys, shouldBePretty(buildOptions)), createReportErrorSummary(buildOptions)); - updateCreateProgram(buildHost); - buildHost.afterProgramEmitAndDiagnostics = program => reportStatistics(program.getProgram()); - const builder = createSolutionBuilder(buildHost, projects, buildOptions); - return sys.exit(buildOptions.clean ? builder.clean() : builder.build()); - } - - function performBuild(args: string[]) { - const { buildOptions, projects, errors } = parseBuildCommand(args); - if (buildOptions.generateCpuProfile && sys.enableCPUProfiler) { - sys.enableCPUProfiler(buildOptions.generateCpuProfile, () => performBuildWorker(buildOptions, projects, errors)); - } - else { - performBuildWorker(buildOptions, projects, errors); - } - } - - function createReportErrorSummary(options: CompilerOptions | BuildOptions): ReportEmitErrorSummary | undefined { - return shouldBePretty(options) ? - errorCount => sys.write(getErrorSummaryText(errorCount, sys.newLine)) : - undefined; - } - - function performCompilation(rootNames: string[], projectReferences: readonly ProjectReference[] | undefined, options: CompilerOptions, configFileParsingDiagnostics?: readonly Diagnostic[]) { - const host = createCompilerHost(options); - const currentDirectory = host.getCurrentDirectory(); - const getCanonicalFileName = createGetCanonicalFileName(host.useCaseSensitiveFileNames()); - changeCompilerHostLikeToUseCache(host, fileName => toPath(fileName, currentDirectory, getCanonicalFileName)); - enableStatistics(options); - - const programOptions: CreateProgramOptions = { - rootNames, - options, - projectReferences, - host, - configFileParsingDiagnostics - }; - const program = createProgram(programOptions); - const exitStatus = emitFilesAndReportErrorsAndGetExitStatus( - program, - reportDiagnostic, - s => sys.write(s + sys.newLine), - createReportErrorSummary(options) - ); - reportStatistics(program); - return sys.exit(exitStatus); - } - - function performIncrementalCompilation(config: ParsedCommandLine) { - const { options, fileNames, projectReferences } = config; - enableStatistics(options); - return sys.exit(ts.performIncrementalCompilation({ - rootNames: fileNames, - options, - configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config), - projectReferences, - reportDiagnostic, - reportErrorSummary: createReportErrorSummary(options), - afterProgramEmitAndDiagnostics: builderProgram => reportStatistics(builderProgram.getProgram()) - })); - } - - function updateCreateProgram(host: { createProgram: CreateProgram; }) { - const compileUsingBuilder = host.createProgram; - host.createProgram = (rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences) => { - Debug.assert(rootNames !== undefined || (options === undefined && !!oldProgram)); - if (options !== undefined) { - enableStatistics(options); - } - return compileUsingBuilder(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences); - }; - } - - function updateWatchCompilationHost(watchCompilerHost: WatchCompilerHost) { - updateCreateProgram(watchCompilerHost); - const emitFilesUsingBuilder = watchCompilerHost.afterProgramCreate!; // TODO: GH#18217 - watchCompilerHost.afterProgramCreate = builderProgram => { - emitFilesUsingBuilder(builderProgram); - reportStatistics(builderProgram.getProgram()); - }; - } - - function createWatchStatusReporter(options: CompilerOptions | BuildOptions) { - return ts.createWatchStatusReporter(sys, shouldBePretty(options)); - } - - function createWatchOfConfigFile(configParseResult: ParsedCommandLine, optionsToExtend: CompilerOptions) { - const watchCompilerHost = createWatchCompilerHostOfConfigFile(configParseResult.options.configFilePath!, optionsToExtend, sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(configParseResult.options)); // TODO: GH#18217 - updateWatchCompilationHost(watchCompilerHost); - watchCompilerHost.configFileParsingResult = configParseResult; - createWatchProgram(watchCompilerHost); - } - - function createWatchOfFilesAndCompilerOptions(rootFiles: string[], options: CompilerOptions) { - const watchCompilerHost = createWatchCompilerHostOfFilesAndCompilerOptions(rootFiles, options, sys, /*createProgram*/ undefined, reportDiagnostic, createWatchStatusReporter(options)); - updateWatchCompilationHost(watchCompilerHost); - createWatchProgram(watchCompilerHost); - } - - function enableStatistics(compilerOptions: CompilerOptions) { - if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { - performance.enable(); - } - } - - function reportStatistics(program: Program) { - let statistics: Statistic[]; - const compilerOptions = program.getCompilerOptions(); - if (compilerOptions.diagnostics || compilerOptions.extendedDiagnostics) { - statistics = []; - const memoryUsed = sys.getMemoryUsage ? sys.getMemoryUsage() : -1; - reportCountStatistic("Files", program.getSourceFiles().length); - reportCountStatistic("Lines", countLines(program)); - reportCountStatistic("Nodes", program.getNodeCount()); - reportCountStatistic("Identifiers", program.getIdentifierCount()); - reportCountStatistic("Symbols", program.getSymbolCount()); - reportCountStatistic("Types", program.getTypeCount()); - - if (memoryUsed >= 0) { - reportStatisticalValue("Memory used", Math.round(memoryUsed / 1000) + "K"); - } - - const programTime = performance.getDuration("Program"); - const bindTime = performance.getDuration("Bind"); - const checkTime = performance.getDuration("Check"); - const emitTime = performance.getDuration("Emit"); - if (compilerOptions.extendedDiagnostics) { - const caches = program.getRelationCacheSizes(); - reportCountStatistic("Assignability cache size", caches.assignable); - reportCountStatistic("Identity cache size", caches.identity); - reportCountStatistic("Subtype cache size", caches.subtype); - performance.forEachMeasure((name, duration) => reportTimeStatistic(`${name} time`, duration)); - } - else { - // Individual component times. - // Note: To match the behavior of previous versions of the compiler, the reported parse time includes - // I/O read time and processing time for triple-slash references and module imports, and the reported - // emit time includes I/O write time. We preserve this behavior so we can accurately compare times. - reportTimeStatistic("I/O read", performance.getDuration("I/O Read")); - reportTimeStatistic("I/O write", performance.getDuration("I/O Write")); - reportTimeStatistic("Parse time", programTime); - reportTimeStatistic("Bind time", bindTime); - reportTimeStatistic("Check time", checkTime); - reportTimeStatistic("Emit time", emitTime); - } - reportTimeStatistic("Total time", programTime + bindTime + checkTime + emitTime); - reportStatistics(); - - performance.disable(); - } - - function reportStatistics() { - let nameSize = 0; - let valueSize = 0; - for (const { name, value } of statistics) { - if (name.length > nameSize) { - nameSize = name.length; - } - - if (value.length > valueSize) { - valueSize = value.length; - } - } - - for (const { name, value } of statistics) { - sys.write(padRight(name + ":", nameSize + 2) + padLeft(value.toString(), valueSize) + sys.newLine); - } - } - - function reportStatisticalValue(name: string, value: string) { - statistics.push({ name, value }); - } - - function reportCountStatistic(name: string, count: number) { - reportStatisticalValue(name, "" + count); - } - - function reportTimeStatistic(name: string, time: number) { - reportStatisticalValue(name, (time / 1000).toFixed(2) + "s"); - } - } - - function writeConfigFile(options: CompilerOptions, fileNames: string[]) { - const currentDirectory = sys.getCurrentDirectory(); - const file = normalizePath(combinePaths(currentDirectory, "tsconfig.json")); - if (sys.fileExists(file)) { - reportDiagnostic(createCompilerDiagnostic(Diagnostics.A_tsconfig_json_file_is_already_defined_at_Colon_0, file)); - } - else { - sys.writeFile(file, generateTSConfig(options, fileNames, sys.newLine)); - reportDiagnostic(createCompilerDiagnostic(Diagnostics.Successfully_created_a_tsconfig_json_file)); - } - - return; - } -} - -if (ts.Debug.isDebugging) { - ts.Debug.enableDebugInfo(); -} - -if (ts.sys.tryEnableSourceMapsForHost && /^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))) { - ts.sys.tryEnableSourceMapsForHost(); -} - -if (ts.sys.setBlocking) { - ts.sys.setBlocking(); -} - -ts.executeCommandLine(ts.sys.args); +// This file actually uses arguments passed on commandline and executes it +ts.executeCommandLine( + ts.sys, + { + onCompilerHostCreate: ts.noop, + onCompilationComplete: ts.noop, + onSolutionBuilderHostCreate: ts.noop, + onSolutionBuildComplete: ts.noop + }, + ts.sys.args +); diff --git a/src/tsc/tsconfig.json b/src/tsc/tsconfig.json index e97cedc5de2..7de3cb82a95 100644 --- a/src/tsc/tsconfig.json +++ b/src/tsc/tsconfig.json @@ -4,6 +4,7 @@ "outFile": "../../built/local/tsc.js" }, "files": [ + "executeCommandLine.ts", "tsc.ts" ], "references": [ diff --git a/src/tsc/tsconfig.release.json b/src/tsc/tsconfig.release.json index 45a7577a342..5d6e1687c24 100644 --- a/src/tsc/tsconfig.release.json +++ b/src/tsc/tsconfig.release.json @@ -1,5 +1,5 @@ { - "extends": "../tsconfig-base", + "extends": "./tsconfig.json", "compilerOptions": { "outFile": "../../built/local/tsc.release.js", "stripInternal": true, @@ -8,11 +8,8 @@ "declarationMap": false, "sourceMap": false, "composite": false, - "incremental": true + "incremental": true }, - "files": [ - "tsc.ts" - ], "references": [ { "path": "../compiler/tsconfig.release.json", "prepend": true } ] diff --git a/src/tsconfig.json b/src/tsconfig.json index 0c7f0c65da0..8a0f4dbce0e 100644 --- a/src/tsconfig.json +++ b/src/tsconfig.json @@ -2,10 +2,12 @@ "files": [], "include": [], "references": [ + { "path": "./shims" }, { "path": "./tsc" }, { "path": "./tsserver" }, { "path": "./typingsInstaller" }, { "path": "./watchGuard" }, + { "path": "./debug" }, { "path": "./cancellationToken" }, { "path": "./testRunner" } ] diff --git a/src/tsserverlibrary/tsconfig.json b/src/tsserverlibrary/tsconfig.json index fcd4597dc6d..f9953772f1f 100644 --- a/src/tsserverlibrary/tsconfig.json +++ b/src/tsserverlibrary/tsconfig.json @@ -7,6 +7,7 @@ "tsserverlibrary.ts" ], "references": [ + { "path": "../shims", "prepend": true }, { "path": "../compiler", "prepend": true }, { "path": "../jsTyping", "prepend": true }, { "path": "../services", "prepend": true }, diff --git a/src/typescriptServices/tsconfig.json b/src/typescriptServices/tsconfig.json index 1845d69a473..33028aad27c 100644 --- a/src/typescriptServices/tsconfig.json +++ b/src/typescriptServices/tsconfig.json @@ -7,6 +7,7 @@ "typescriptServices.ts" ], "references": [ + { "path": "../shims", "prepend": true }, { "path": "../compiler", "prepend": true }, { "path": "../jsTyping", "prepend": true }, { "path": "../services", "prepend": true } diff --git a/tests/baselines/reference/aliasErrors.errors.txt b/tests/baselines/reference/aliasErrors.errors.txt index 42b84993ba2..bb257f5337c 100644 --- a/tests/baselines/reference/aliasErrors.errors.txt +++ b/tests/baselines/reference/aliasErrors.errors.txt @@ -2,7 +2,7 @@ tests/cases/compiler/aliasErrors.ts(11,12): error TS2503: Cannot find namespace tests/cases/compiler/aliasErrors.ts(12,13): error TS2503: Cannot find namespace 'no'. tests/cases/compiler/aliasErrors.ts(13,12): error TS1003: Identifier expected. tests/cases/compiler/aliasErrors.ts(14,12): error TS1003: Identifier expected. -tests/cases/compiler/aliasErrors.ts(15,12): error TS1003: Identifier expected. +tests/cases/compiler/aliasErrors.ts(15,12): error TS1359: Identifier expected. 'null' is a reserved word that cannot be used here. tests/cases/compiler/aliasErrors.ts(16,12): error TS2503: Cannot find namespace 'undefined'. tests/cases/compiler/aliasErrors.ts(26,15): error TS2694: Namespace 'foo.bar.baz' has no exported member 'bar'. @@ -32,7 +32,7 @@ tests/cases/compiler/aliasErrors.ts(26,15): error TS2694: Namespace 'foo.bar.baz !!! error TS1003: Identifier expected. import q = null; ~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'null' is a reserved word that cannot be used here. import r = undefined; ~~~~~~~~~ !!! error TS2503: Cannot find namespace 'undefined'. diff --git a/tests/baselines/reference/api/tsserverlibrary.d.ts b/tests/baselines/reference/api/tsserverlibrary.d.ts index 5ad30ae8803..b02074e75ef 100644 --- a/tests/baselines/reference/api/tsserverlibrary.d.ts +++ b/tests/baselines/reference/api/tsserverlibrary.d.ts @@ -1964,6 +1964,8 @@ declare namespace ts { DiagnosticsPresent_OutputsSkipped = 1, DiagnosticsPresent_OutputsGenerated = 2, InvalidProject_OutputsSkipped = 3, + ProjectReferenceCycle_OutputsSkipped = 4, + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ProjectReferenceCycle_OutputsSkupped = 4 } export interface EmitResult { @@ -3169,6 +3171,7 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ @@ -4902,6 +4905,9 @@ declare namespace ts { isClassOrInterface(): this is InterfaceType; isClass(): this is InterfaceType; } + interface TypeReference { + typeArguments?: readonly Type[]; + } interface Signature { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; @@ -5068,7 +5074,7 @@ declare namespace ts { getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; dispose(): void; } @@ -5191,7 +5197,7 @@ declare namespace ts { } interface FileTextChanges { fileName: string; - textChanges: TextChange[]; + textChanges: readonly TextChange[]; isNewFile?: boolean; } interface CodeAction { @@ -6623,9 +6629,11 @@ declare namespace ts.server.protocol { interface DefinitionResponse extends Response { body?: FileSpanWithContext[]; } - interface DefinitionInfoAndBoundSpanReponse extends Response { + interface DefinitionInfoAndBoundSpanResponse extends Response { body?: DefinitionInfoAndBoundSpan; } + /** @deprecated Use `DefinitionInfoAndBoundSpanResponse` instead. */ + type DefinitionInfoAndBoundSpanReponse = DefinitionInfoAndBoundSpanResponse; /** * Definition response message. Gives text range for definition. */ @@ -8288,6 +8296,12 @@ declare namespace ts.server.protocol { * For those entries, The `insertText` and `replacementSpan` properties will be set to change from `.x` property access to `["x"]`. */ readonly includeCompletionsWithInsertText?: boolean; + /** + * Unless this option is `false`, or `includeCompletionsWithInsertText` is not enabled, + * member completion lists triggered with `.` will include entries on potentially-null and potentially-undefined + * values, with insertion text to replace preceding `.` tokens with `?.`. + */ + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly allowTextChangesInNewFiles?: boolean; readonly lazyConfiguredProjectsFromExternalProject?: boolean; diff --git a/tests/baselines/reference/api/typescript.d.ts b/tests/baselines/reference/api/typescript.d.ts index 7bf245876e5..7361ccb6768 100644 --- a/tests/baselines/reference/api/typescript.d.ts +++ b/tests/baselines/reference/api/typescript.d.ts @@ -1964,6 +1964,8 @@ declare namespace ts { DiagnosticsPresent_OutputsSkipped = 1, DiagnosticsPresent_OutputsGenerated = 2, InvalidProject_OutputsSkipped = 3, + ProjectReferenceCycle_OutputsSkipped = 4, + /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */ ProjectReferenceCycle_OutputsSkupped = 4 } export interface EmitResult { @@ -3169,6 +3171,7 @@ declare namespace ts { readonly disableSuggestions?: boolean; readonly quotePreference?: "auto" | "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly includeCompletionsWithInsertText?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; /** Determines whether we import `foo/index.ts` as "foo", "foo/index", or "foo/index.js" */ @@ -4902,6 +4905,9 @@ declare namespace ts { isClassOrInterface(): this is InterfaceType; isClass(): this is InterfaceType; } + interface TypeReference { + typeArguments?: readonly Type[]; + } interface Signature { getDeclaration(): SignatureDeclaration; getTypeParameters(): TypeParameter[] | undefined; @@ -5068,7 +5074,7 @@ declare namespace ts { getEditsForRefactor(fileName: string, formatOptions: FormatCodeSettings, positionOrRange: number | TextRange, refactorName: string, actionName: string, preferences: UserPreferences | undefined): RefactorEditInfo | undefined; organizeImports(scope: OrganizeImportsScope, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; getEditsForFileRename(oldFilePath: string, newFilePath: string, formatOptions: FormatCodeSettings, preferences: UserPreferences | undefined): readonly FileTextChanges[]; - getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean): EmitOutput; + getEmitOutput(fileName: string, emitOnlyDtsFiles?: boolean, forceDtsEmit?: boolean): EmitOutput; getProgram(): Program | undefined; dispose(): void; } @@ -5191,7 +5197,7 @@ declare namespace ts { } interface FileTextChanges { fileName: string; - textChanges: TextChange[]; + textChanges: readonly TextChange[]; isNewFile?: boolean; } interface CodeAction { diff --git a/tests/baselines/reference/arraySigChecking.errors.txt b/tests/baselines/reference/arraySigChecking.errors.txt index a1f219919d8..5bf4cfdd58e 100644 --- a/tests/baselines/reference/arraySigChecking.errors.txt +++ b/tests/baselines/reference/arraySigChecking.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/arraySigChecking.ts(11,17): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/arraySigChecking.ts(11,17): error TS1023: An index signature parameter type must be either 'string' or 'number'. tests/cases/compiler/arraySigChecking.ts(18,27): error TS2322: Type 'void' is not assignable to type 'string'. tests/cases/compiler/arraySigChecking.ts(22,13): error TS2322: Type 'number' is not assignable to type 'number[]'. tests/cases/compiler/arraySigChecking.ts(22,16): error TS2322: Type 'number' is not assignable to type 'number[]'. @@ -17,7 +17,7 @@ tests/cases/compiler/arraySigChecking.ts(22,16): error TS2322: Type 'number' is var foo: { [index: any]; }; // expect an error here ~~~~~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } interface myInt { diff --git a/tests/baselines/reference/assertionTypePredicates1.errors.txt b/tests/baselines/reference/assertionTypePredicates1.errors.txt index 2fe95b99548..cefd25aa139 100644 --- a/tests/baselines/reference/assertionTypePredicates1.errors.txt +++ b/tests/baselines/reference/assertionTypePredicates1.errors.txt @@ -1,16 +1,20 @@ -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(116,37): error TS1228: A type predicate is only allowed in return type position for functions and methods. -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(117,37): error TS1228: A type predicate is only allowed in return type position for functions and methods. -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(118,37): error TS1228: A type predicate is only allowed in return type position for functions and methods. -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(121,15): error TS1228: A type predicate is only allowed in return type position for functions and methods. -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(122,15): error TS1228: A type predicate is only allowed in return type position for functions and methods. -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(123,15): error TS1228: A type predicate is only allowed in return type position for functions and methods. -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(124,15): error TS1228: A type predicate is only allowed in return type position for functions and methods. -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(129,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(131,5): error TS2776: Assertions require the call target to be an identifier or qualified name. -tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(133,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(39,9): error TS7027: Unreachable code detected. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(43,9): error TS7027: Unreachable code detected. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(87,9): error TS7027: Unreachable code detected. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(122,9): error TS7027: Unreachable code detected. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(132,37): error TS1228: A type predicate is only allowed in return type position for functions and methods. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(133,37): error TS1228: A type predicate is only allowed in return type position for functions and methods. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(134,37): error TS1228: A type predicate is only allowed in return type position for functions and methods. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(137,15): error TS1228: A type predicate is only allowed in return type position for functions and methods. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(138,15): error TS1228: A type predicate is only allowed in return type position for functions and methods. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(139,15): error TS1228: A type predicate is only allowed in return type position for functions and methods. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(140,15): error TS1228: A type predicate is only allowed in return type position for functions and methods. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(145,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(147,5): error TS2776: Assertions require the call target to be an identifier or qualified name. +tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(149,5): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. -==== tests/cases/conformance/controlFlow/assertionTypePredicates1.ts (10 errors) ==== +==== tests/cases/conformance/controlFlow/assertionTypePredicates1.ts (14 errors) ==== declare function isString(value: unknown): value is string; declare function isArrayOfStrings(value: unknown): value is string[]; @@ -47,6 +51,18 @@ tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(133,5): error TS assertDefined(x); x; // string } + if (!!true) { + assert(false); + x; // Unreachable + ~~ +!!! error TS7027: Unreachable code detected. + } + if (!!true) { + assert(false && x === undefined); + x; // Unreachable + ~~ +!!! error TS7027: Unreachable code detected. + } } function f02(x: string | undefined) { @@ -87,6 +103,12 @@ tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(133,5): error TS Debug.assertDefined(x); x.length; } + if (!!true) { + Debug.assert(false); + x; // Unreachable + ~~ +!!! error TS7027: Unreachable code detected. + } } class Test { @@ -118,6 +140,12 @@ tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(133,5): error TS this.assertIsTest2(); this.z; } + baz(x: number) { + this.assert(false); + x; // Unreachable + ~~ +!!! error TS7027: Unreachable code detected. + } } class Test2 extends Test { @@ -156,7 +184,7 @@ tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(133,5): error TS assert(typeof x === "string"); // Error ~~~~~~ !!! error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. -!!! related TS2728 tests/cases/conformance/controlFlow/assertionTypePredicates1.ts:128:11: 'assert' is declared here. +!!! related TS2728 tests/cases/conformance/controlFlow/assertionTypePredicates1.ts:144:11: 'assert' is declared here. const a = [assert]; a[0](typeof x === "string"); // Error ~~~~ @@ -165,7 +193,7 @@ tests/cases/conformance/controlFlow/assertionTypePredicates1.ts(133,5): error TS t1.assert(typeof x === "string"); // Error ~~~~~~~~~ !!! error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. -!!! related TS2728 tests/cases/conformance/controlFlow/assertionTypePredicates1.ts:132:11: 't1' is declared here. +!!! related TS2728 tests/cases/conformance/controlFlow/assertionTypePredicates1.ts:148:11: 't1' is declared here. const t2: Test = new Test(); t2.assert(typeof x === "string"); } diff --git a/tests/baselines/reference/assertionTypePredicates1.js b/tests/baselines/reference/assertionTypePredicates1.js index 145bb98bce9..8077e87a797 100644 --- a/tests/baselines/reference/assertionTypePredicates1.js +++ b/tests/baselines/reference/assertionTypePredicates1.js @@ -35,6 +35,14 @@ function f01(x: unknown) { assertDefined(x); x; // string } + if (!!true) { + assert(false); + x; // Unreachable + } + if (!!true) { + assert(false && x === undefined); + x; // Unreachable + } } function f02(x: string | undefined) { @@ -75,6 +83,10 @@ function f10(x: string | undefined) { Debug.assertDefined(x); x.length; } + if (!!true) { + Debug.assert(false); + x; // Unreachable + } } class Test { @@ -106,6 +118,10 @@ class Test { this.assertIsTest2(); this.z; } + baz(x: number) { + this.assert(false); + x; // Unreachable + } } class Test2 extends Test { @@ -180,6 +196,14 @@ function f01(x) { assertDefined(x); x; // string } + if (!!true) { + assert(false); + x; // Unreachable + } + if (!!true) { + assert(false && x === undefined); + x; // Unreachable + } } function f02(x) { if (!!true) { @@ -215,6 +239,10 @@ function f10(x) { Debug.assertDefined(x); x.length; } + if (!!true) { + Debug.assert(false); + x; // Unreachable + } } var Test = /** @class */ (function () { function Test() { @@ -250,6 +278,10 @@ var Test = /** @class */ (function () { this.assertIsTest2(); this.z; }; + Test.prototype.baz = function (x) { + this.assert(false); + x; // Unreachable + }; return Test; }()); var Test2 = /** @class */ (function (_super) { @@ -295,6 +327,7 @@ declare class Test { assertThis(): asserts this; bar(): void; foo(x: unknown): void; + baz(x: number): void; } declare class Test2 extends Test { z: number; diff --git a/tests/baselines/reference/assertionTypePredicates1.symbols b/tests/baselines/reference/assertionTypePredicates1.symbols index af43ab29864..758d5eddfe9 100644 --- a/tests/baselines/reference/assertionTypePredicates1.symbols +++ b/tests/baselines/reference/assertionTypePredicates1.symbols @@ -106,297 +106,334 @@ function f01(x: unknown) { >x : Symbol(x, Decl(assertionTypePredicates1.ts, 9, 13)) x; // string +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 9, 13)) + } + if (!!true) { + assert(false); +>assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 3, 5)) + + x; // Unreachable +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 9, 13)) + } + if (!!true) { + assert(false && x === undefined); +>assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 3, 5)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 9, 13)) +>undefined : Symbol(undefined) + + x; // Unreachable >x : Symbol(x, Decl(assertionTypePredicates1.ts, 9, 13)) } } function f02(x: string | undefined) { ->f02 : Symbol(f02, Decl(assertionTypePredicates1.ts, 36, 1)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 38, 13)) +>f02 : Symbol(f02, Decl(assertionTypePredicates1.ts, 44, 1)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 46, 13)) if (!!true) { assert(x); >assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 3, 5)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 38, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 46, 13)) x.length; >x.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 38, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 46, 13)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) } if (!!true) { assert(x !== undefined); >assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 3, 5)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 38, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 46, 13)) >undefined : Symbol(undefined) x.length; >x.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 38, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 46, 13)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) } if (!!true) { assertDefined(x); >assertDefined : Symbol(assertDefined, Decl(assertionTypePredicates1.ts, 6, 83)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 38, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 46, 13)) x.length; >x.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 38, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 46, 13)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) } } function f03(x: string | undefined, assert: (value: unknown) => asserts value) { ->f03 : Symbol(f03, Decl(assertionTypePredicates1.ts, 51, 1)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 53, 13)) ->assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 53, 35)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 53, 45)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 53, 45)) +>f03 : Symbol(f03, Decl(assertionTypePredicates1.ts, 59, 1)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 61, 13)) +>assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 61, 35)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 61, 45)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 61, 45)) assert(x); ->assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 53, 35)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 53, 13)) +>assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 61, 35)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 61, 13)) x.length; >x.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 53, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 61, 13)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) } namespace Debug { ->Debug : Symbol(Debug, Decl(assertionTypePredicates1.ts, 56, 1)) +>Debug : Symbol(Debug, Decl(assertionTypePredicates1.ts, 64, 1)) export declare function assert(value: unknown, message?: string): asserts value; ->assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 58, 17)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 59, 35)) ->message : Symbol(message, Decl(assertionTypePredicates1.ts, 59, 50)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 59, 35)) +>assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 66, 17)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 67, 35)) +>message : Symbol(message, Decl(assertionTypePredicates1.ts, 67, 50)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 67, 35)) export declare function assertDefined(value: T): asserts value is NonNullable; ->assertDefined : Symbol(assertDefined, Decl(assertionTypePredicates1.ts, 59, 84)) ->T : Symbol(T, Decl(assertionTypePredicates1.ts, 60, 42)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 60, 45)) ->T : Symbol(T, Decl(assertionTypePredicates1.ts, 60, 42)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 60, 45)) +>assertDefined : Symbol(assertDefined, Decl(assertionTypePredicates1.ts, 67, 84)) +>T : Symbol(T, Decl(assertionTypePredicates1.ts, 68, 42)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 68, 45)) +>T : Symbol(T, Decl(assertionTypePredicates1.ts, 68, 42)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 68, 45)) >NonNullable : Symbol(NonNullable, Decl(lib.es5.d.ts, --, --)) ->T : Symbol(T, Decl(assertionTypePredicates1.ts, 60, 42)) +>T : Symbol(T, Decl(assertionTypePredicates1.ts, 68, 42)) } function f10(x: string | undefined) { ->f10 : Symbol(f10, Decl(assertionTypePredicates1.ts, 61, 1)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 63, 13)) +>f10 : Symbol(f10, Decl(assertionTypePredicates1.ts, 69, 1)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 71, 13)) if (!!true) { Debug.assert(x); ->Debug.assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 58, 17)) ->Debug : Symbol(Debug, Decl(assertionTypePredicates1.ts, 56, 1)) ->assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 58, 17)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 63, 13)) +>Debug.assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 66, 17)) +>Debug : Symbol(Debug, Decl(assertionTypePredicates1.ts, 64, 1)) +>assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 66, 17)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 71, 13)) x.length; >x.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 63, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 71, 13)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) } if (!!true) { Debug.assert(x !== undefined); ->Debug.assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 58, 17)) ->Debug : Symbol(Debug, Decl(assertionTypePredicates1.ts, 56, 1)) ->assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 58, 17)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 63, 13)) +>Debug.assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 66, 17)) +>Debug : Symbol(Debug, Decl(assertionTypePredicates1.ts, 64, 1)) +>assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 66, 17)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 71, 13)) >undefined : Symbol(undefined) x.length; >x.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 63, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 71, 13)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) } if (!!true) { Debug.assertDefined(x); ->Debug.assertDefined : Symbol(Debug.assertDefined, Decl(assertionTypePredicates1.ts, 59, 84)) ->Debug : Symbol(Debug, Decl(assertionTypePredicates1.ts, 56, 1)) ->assertDefined : Symbol(Debug.assertDefined, Decl(assertionTypePredicates1.ts, 59, 84)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 63, 13)) +>Debug.assertDefined : Symbol(Debug.assertDefined, Decl(assertionTypePredicates1.ts, 67, 84)) +>Debug : Symbol(Debug, Decl(assertionTypePredicates1.ts, 64, 1)) +>assertDefined : Symbol(Debug.assertDefined, Decl(assertionTypePredicates1.ts, 67, 84)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 71, 13)) x.length; >x.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 63, 13)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 71, 13)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) } + if (!!true) { + Debug.assert(false); +>Debug.assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 66, 17)) +>Debug : Symbol(Debug, Decl(assertionTypePredicates1.ts, 64, 1)) +>assert : Symbol(Debug.assert, Decl(assertionTypePredicates1.ts, 66, 17)) + + x; // Unreachable +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 71, 13)) + } } class Test { ->Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) +>Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) assert(value: unknown): asserts value { ->assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 78, 12)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 79, 11)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 79, 11)) +>assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 90, 12)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 91, 11)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 91, 11)) if (value) return; ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 79, 11)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 91, 11)) throw new Error(); >Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) } isTest2(): this is Test2 { ->isTest2 : Symbol(Test.isTest2, Decl(assertionTypePredicates1.ts, 82, 5)) ->Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 107, 1)) +>isTest2 : Symbol(Test.isTest2, Decl(assertionTypePredicates1.ts, 94, 5)) +>Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 123, 1)) return this instanceof Test2; ->this : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) ->Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 107, 1)) +>this : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) +>Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 123, 1)) } assertIsTest2(): asserts this is Test2 { ->assertIsTest2 : Symbol(Test.assertIsTest2, Decl(assertionTypePredicates1.ts, 85, 5)) ->Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 107, 1)) +>assertIsTest2 : Symbol(Test.assertIsTest2, Decl(assertionTypePredicates1.ts, 97, 5)) +>Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 123, 1)) if (this instanceof Test2) return; ->this : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) ->Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 107, 1)) +>this : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) +>Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 123, 1)) throw new Error(); >Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) } assertThis(): asserts this { ->assertThis : Symbol(Test.assertThis, Decl(assertionTypePredicates1.ts, 89, 5)) +>assertThis : Symbol(Test.assertThis, Decl(assertionTypePredicates1.ts, 101, 5)) if (!this) return; ->this : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) +>this : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) throw new Error(); >Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) } bar() { ->bar : Symbol(Test.bar, Decl(assertionTypePredicates1.ts, 93, 5)) +>bar : Symbol(Test.bar, Decl(assertionTypePredicates1.ts, 105, 5)) this.assertThis(); ->this.assertThis : Symbol(Test.assertThis, Decl(assertionTypePredicates1.ts, 89, 5)) ->this : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) ->assertThis : Symbol(Test.assertThis, Decl(assertionTypePredicates1.ts, 89, 5)) +>this.assertThis : Symbol(Test.assertThis, Decl(assertionTypePredicates1.ts, 101, 5)) +>this : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) +>assertThis : Symbol(Test.assertThis, Decl(assertionTypePredicates1.ts, 101, 5)) this; ->this : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) +>this : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) } foo(x: unknown) { ->foo : Symbol(Test.foo, Decl(assertionTypePredicates1.ts, 97, 5)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 98, 8)) +>foo : Symbol(Test.foo, Decl(assertionTypePredicates1.ts, 109, 5)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 110, 8)) this.assert(typeof x === "string"); ->this.assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 78, 12)) ->this : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) ->assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 78, 12)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 98, 8)) +>this.assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 90, 12)) +>this : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) +>assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 90, 12)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 110, 8)) x.length; >x.length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 98, 8)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 110, 8)) >length : Symbol(String.length, Decl(lib.es5.d.ts, --, --)) if (this.isTest2()) { ->this.isTest2 : Symbol(Test.isTest2, Decl(assertionTypePredicates1.ts, 82, 5)) ->this : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) ->isTest2 : Symbol(Test.isTest2, Decl(assertionTypePredicates1.ts, 82, 5)) +>this.isTest2 : Symbol(Test.isTest2, Decl(assertionTypePredicates1.ts, 94, 5)) +>this : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) +>isTest2 : Symbol(Test.isTest2, Decl(assertionTypePredicates1.ts, 94, 5)) this.z; ->this.z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 109, 26)) ->z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 109, 26)) +>this.z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 125, 26)) +>z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 125, 26)) } this.assertIsTest2(); ->this.assertIsTest2 : Symbol(Test.assertIsTest2, Decl(assertionTypePredicates1.ts, 85, 5)) ->this : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) ->assertIsTest2 : Symbol(Test.assertIsTest2, Decl(assertionTypePredicates1.ts, 85, 5)) +>this.assertIsTest2 : Symbol(Test.assertIsTest2, Decl(assertionTypePredicates1.ts, 97, 5)) +>this : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) +>assertIsTest2 : Symbol(Test.assertIsTest2, Decl(assertionTypePredicates1.ts, 97, 5)) this.z; ->this.z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 109, 26)) ->z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 109, 26)) +>this.z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 125, 26)) +>z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 125, 26)) + } + baz(x: number) { +>baz : Symbol(Test.baz, Decl(assertionTypePredicates1.ts, 118, 5)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 119, 8)) + + this.assert(false); +>this.assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 90, 12)) +>this : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) +>assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 90, 12)) + + x; // Unreachable +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 119, 8)) } } class Test2 extends Test { ->Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 107, 1)) ->Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) +>Test2 : Symbol(Test2, Decl(assertionTypePredicates1.ts, 123, 1)) +>Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) z = 0; ->z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 109, 26)) +>z : Symbol(Test2.z, Decl(assertionTypePredicates1.ts, 125, 26)) } // Invalid constructs declare let Q1: new (x: unknown) => x is string; ->Q1 : Symbol(Q1, Decl(assertionTypePredicates1.ts, 115, 11)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 115, 21)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 115, 21)) +>Q1 : Symbol(Q1, Decl(assertionTypePredicates1.ts, 131, 11)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 131, 21)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 131, 21)) declare let Q2: new (x: boolean) => asserts x; ->Q2 : Symbol(Q2, Decl(assertionTypePredicates1.ts, 116, 11)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 116, 21)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 116, 21)) +>Q2 : Symbol(Q2, Decl(assertionTypePredicates1.ts, 132, 11)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 132, 21)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 132, 21)) declare let Q3: new (x: unknown) => asserts x is string; ->Q3 : Symbol(Q3, Decl(assertionTypePredicates1.ts, 117, 11)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 117, 21)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 117, 21)) +>Q3 : Symbol(Q3, Decl(assertionTypePredicates1.ts, 133, 11)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 133, 21)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 133, 21)) declare class Wat { ->Wat : Symbol(Wat, Decl(assertionTypePredicates1.ts, 117, 56)) +>Wat : Symbol(Wat, Decl(assertionTypePredicates1.ts, 133, 56)) get p1(): this is string; ->p1 : Symbol(Wat.p1, Decl(assertionTypePredicates1.ts, 119, 19), Decl(assertionTypePredicates1.ts, 120, 29)) +>p1 : Symbol(Wat.p1, Decl(assertionTypePredicates1.ts, 135, 19), Decl(assertionTypePredicates1.ts, 136, 29)) set p1(x: this is string); ->p1 : Symbol(Wat.p1, Decl(assertionTypePredicates1.ts, 119, 19), Decl(assertionTypePredicates1.ts, 120, 29)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 121, 11)) +>p1 : Symbol(Wat.p1, Decl(assertionTypePredicates1.ts, 135, 19), Decl(assertionTypePredicates1.ts, 136, 29)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 137, 11)) get p2(): asserts this is string; ->p2 : Symbol(Wat.p2, Decl(assertionTypePredicates1.ts, 121, 30), Decl(assertionTypePredicates1.ts, 122, 37)) +>p2 : Symbol(Wat.p2, Decl(assertionTypePredicates1.ts, 137, 30), Decl(assertionTypePredicates1.ts, 138, 37)) set p2(x: asserts this is string); ->p2 : Symbol(Wat.p2, Decl(assertionTypePredicates1.ts, 121, 30), Decl(assertionTypePredicates1.ts, 122, 37)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 123, 11)) +>p2 : Symbol(Wat.p2, Decl(assertionTypePredicates1.ts, 137, 30), Decl(assertionTypePredicates1.ts, 138, 37)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 139, 11)) } function f20(x: unknown) { ->f20 : Symbol(f20, Decl(assertionTypePredicates1.ts, 124, 1)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 126, 13)) +>f20 : Symbol(f20, Decl(assertionTypePredicates1.ts, 140, 1)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 142, 13)) const assert = (value: unknown): asserts value => {} ->assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 127, 9)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 127, 20)) ->value : Symbol(value, Decl(assertionTypePredicates1.ts, 127, 20)) +>assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 143, 9)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 143, 20)) +>value : Symbol(value, Decl(assertionTypePredicates1.ts, 143, 20)) assert(typeof x === "string"); // Error ->assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 127, 9)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 126, 13)) +>assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 143, 9)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 142, 13)) const a = [assert]; ->a : Symbol(a, Decl(assertionTypePredicates1.ts, 129, 9)) ->assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 127, 9)) +>a : Symbol(a, Decl(assertionTypePredicates1.ts, 145, 9)) +>assert : Symbol(assert, Decl(assertionTypePredicates1.ts, 143, 9)) a[0](typeof x === "string"); // Error ->a : Symbol(a, Decl(assertionTypePredicates1.ts, 129, 9)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 126, 13)) +>a : Symbol(a, Decl(assertionTypePredicates1.ts, 145, 9)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 142, 13)) const t1 = new Test(); ->t1 : Symbol(t1, Decl(assertionTypePredicates1.ts, 131, 9)) ->Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) +>t1 : Symbol(t1, Decl(assertionTypePredicates1.ts, 147, 9)) +>Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) t1.assert(typeof x === "string"); // Error ->t1.assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 78, 12)) ->t1 : Symbol(t1, Decl(assertionTypePredicates1.ts, 131, 9)) ->assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 78, 12)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 126, 13)) +>t1.assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 90, 12)) +>t1 : Symbol(t1, Decl(assertionTypePredicates1.ts, 147, 9)) +>assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 90, 12)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 142, 13)) const t2: Test = new Test(); ->t2 : Symbol(t2, Decl(assertionTypePredicates1.ts, 133, 9)) ->Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) ->Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 76, 1)) +>t2 : Symbol(t2, Decl(assertionTypePredicates1.ts, 149, 9)) +>Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) +>Test : Symbol(Test, Decl(assertionTypePredicates1.ts, 88, 1)) t2.assert(typeof x === "string"); ->t2.assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 78, 12)) ->t2 : Symbol(t2, Decl(assertionTypePredicates1.ts, 133, 9)) ->assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 78, 12)) ->x : Symbol(x, Decl(assertionTypePredicates1.ts, 126, 13)) +>t2.assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 90, 12)) +>t2 : Symbol(t2, Decl(assertionTypePredicates1.ts, 149, 9)) +>assert : Symbol(Test.assert, Decl(assertionTypePredicates1.ts, 90, 12)) +>x : Symbol(x, Decl(assertionTypePredicates1.ts, 142, 13)) } diff --git a/tests/baselines/reference/assertionTypePredicates1.types b/tests/baselines/reference/assertionTypePredicates1.types index 470478b3fe4..ac4100fb449 100644 --- a/tests/baselines/reference/assertionTypePredicates1.types +++ b/tests/baselines/reference/assertionTypePredicates1.types @@ -151,6 +151,36 @@ function f01(x: unknown) { x; // string >x : string } + if (!!true) { +>!!true : true +>!true : false +>true : true + + assert(false); +>assert(false) : void +>assert : (value: unknown) => asserts value +>false : false + + x; // Unreachable +>x : unknown + } + if (!!true) { +>!!true : true +>!true : false +>true : true + + assert(false && x === undefined); +>assert(false && x === undefined) : void +>assert : (value: unknown) => asserts value +>false && x === undefined : false +>false : false +>x === undefined : boolean +>x : unknown +>undefined : undefined + + x; // Unreachable +>x : unknown + } } function f02(x: string | undefined) { @@ -293,6 +323,21 @@ function f10(x: string | undefined) { >x : string >length : number } + if (!!true) { +>!!true : true +>!true : false +>true : true + + Debug.assert(false); +>Debug.assert(false) : void +>Debug.assert : (value: unknown, message?: string | undefined) => asserts value +>Debug : typeof Debug +>assert : (value: unknown, message?: string | undefined) => asserts value +>false : false + + x; // Unreachable +>x : string | undefined + } } class Test { @@ -393,6 +438,20 @@ class Test { >this : this & Test2 >z : number } + baz(x: number) { +>baz : (x: number) => void +>x : number + + this.assert(false); +>this.assert(false) : void +>this.assert : (value: unknown) => asserts value +>this : this +>assert : (value: unknown) => asserts value +>false : false + + x; // Unreachable +>x : number + } } class Test2 extends Test { diff --git a/tests/baselines/reference/bigintIndex.errors.txt b/tests/baselines/reference/bigintIndex.errors.txt index 50e360a1905..9630692d723 100644 --- a/tests/baselines/reference/bigintIndex.errors.txt +++ b/tests/baselines/reference/bigintIndex.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/a.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/a.ts(2,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. tests/cases/compiler/a.ts(8,11): error TS2538: Type '1n' cannot be used as an index type. tests/cases/compiler/a.ts(14,1): error TS2322: Type '123n' is not assignable to type 'string | number | symbol'. tests/cases/compiler/a.ts(19,12): error TS2538: Type 'bigint' cannot be used as an index type. @@ -13,7 +13,7 @@ tests/cases/compiler/b.ts(4,12): error TS2464: A computed property name must be interface BigIntIndex { [index: bigint]: E; // should error ~~~~~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } const arr: number[] = [1, 2, 3]; diff --git a/tests/baselines/reference/callChain.js b/tests/baselines/reference/callChain.js index 1ef797b5ad1..439c38e8b83 100644 --- a/tests/baselines/reference/callChain.js +++ b/tests/baselines/reference/callChain.js @@ -31,7 +31,11 @@ o3["b"]?.(1, ...[2, 3], 4).c; declare const o4: undefined | ((f: (a: T) => T) => T); declare function incr(x: number): number; -const v: number | undefined = o4?.(incr); +const v: number | undefined = o4?.(incr); + +// GH#33744 +declare const o5: () => undefined | (() => void); +o5()?.(); //// [callChain.js] "use strict"; @@ -42,7 +46,7 @@ var __spreadArrays = (this && this.__spreadArrays) || function () { r[k] = a[j]; return r; }; -var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12; +var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x, _y, _z, _0, _1, _2, _3, _4, _5, _6, _7, _8, _9, _10, _11, _12, _13; (_a = o1) === null || _a === void 0 ? void 0 : _a(); (_b = o1) === null || _b === void 0 ? void 0 : _b(1); (_c = o1) === null || _c === void 0 ? void 0 : _c.apply(void 0, [1, 2]); @@ -68,3 +72,4 @@ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, (_9 = (_8 = o3)["b"]) === null || _9 === void 0 ? void 0 : _9.call.apply(_9, __spreadArrays([_8], [1, 2])).c; (_11 = (_10 = o3)["b"]) === null || _11 === void 0 ? void 0 : _11.call.apply(_11, __spreadArrays([_10, 1], [2, 3], [4])).c; var v = (_12 = o4) === null || _12 === void 0 ? void 0 : _12(incr); +(_13 = o5()) === null || _13 === void 0 ? void 0 : _13(); diff --git a/tests/baselines/reference/callChain.symbols b/tests/baselines/reference/callChain.symbols index dd52388bda6..d0a266c41ea 100644 --- a/tests/baselines/reference/callChain.symbols +++ b/tests/baselines/reference/callChain.symbols @@ -148,3 +148,11 @@ const v: number | undefined = o4?.(incr); >o4 : Symbol(o4, Decl(callChain.ts, 30, 13)) >incr : Symbol(incr, Decl(callChain.ts, 30, 57)) +// GH#33744 +declare const o5: () => undefined | (() => void); +>o5 : Symbol(o5, Decl(callChain.ts, 35, 13)) +>T : Symbol(T, Decl(callChain.ts, 35, 19)) + +o5()?.(); +>o5 : Symbol(o5, Decl(callChain.ts, 35, 13)) + diff --git a/tests/baselines/reference/callChain.types b/tests/baselines/reference/callChain.types index 70f835bf568..6ba17855cb3 100644 --- a/tests/baselines/reference/callChain.types +++ b/tests/baselines/reference/callChain.types @@ -255,3 +255,12 @@ const v: number | undefined = o4?.(incr); >o4 : ((f: (a: T) => T) => T) | undefined >incr : (x: number) => number +// GH#33744 +declare const o5: () => undefined | (() => void); +>o5 : () => (() => void) | undefined + +o5()?.(); +>o5()?.() : void | undefined +>o5() : (() => void) | undefined +>o5 : () => (() => void) | undefined + diff --git a/tests/baselines/reference/callOfPropertylessConstructorFunction.errors.txt b/tests/baselines/reference/callOfPropertylessConstructorFunction.errors.txt new file mode 100644 index 00000000000..0abc6cf8d0c --- /dev/null +++ b/tests/baselines/reference/callOfPropertylessConstructorFunction.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/jsdoc/callOfPropertylessConstructorFunction.js(7,1): error TS2348: Value of type 'typeof Dependency' is not callable. Did you mean to include 'new'? + + +==== tests/cases/conformance/jsdoc/callOfPropertylessConstructorFunction.js (1 errors) ==== + /** + * @constructor + */ + function Dependency(j) { + return j + } + Dependency({}) + ~~~~~~~~~~~~~~ +!!! error TS2348: Value of type 'typeof Dependency' is not callable. Did you mean to include 'new'? + \ No newline at end of file diff --git a/tests/baselines/reference/callOfPropertylessConstructorFunction.symbols b/tests/baselines/reference/callOfPropertylessConstructorFunction.symbols new file mode 100644 index 00000000000..94ebfa6cef2 --- /dev/null +++ b/tests/baselines/reference/callOfPropertylessConstructorFunction.symbols @@ -0,0 +1,14 @@ +=== tests/cases/conformance/jsdoc/callOfPropertylessConstructorFunction.js === +/** + * @constructor + */ +function Dependency(j) { +>Dependency : Symbol(Dependency, Decl(callOfPropertylessConstructorFunction.js, 0, 0)) +>j : Symbol(j, Decl(callOfPropertylessConstructorFunction.js, 3, 20)) + + return j +>j : Symbol(j, Decl(callOfPropertylessConstructorFunction.js, 3, 20)) +} +Dependency({}) +>Dependency : Symbol(Dependency, Decl(callOfPropertylessConstructorFunction.js, 0, 0)) + diff --git a/tests/baselines/reference/callOfPropertylessConstructorFunction.types b/tests/baselines/reference/callOfPropertylessConstructorFunction.types new file mode 100644 index 00000000000..1294e4164c4 --- /dev/null +++ b/tests/baselines/reference/callOfPropertylessConstructorFunction.types @@ -0,0 +1,16 @@ +=== tests/cases/conformance/jsdoc/callOfPropertylessConstructorFunction.js === +/** + * @constructor + */ +function Dependency(j) { +>Dependency : typeof Dependency +>j : any + + return j +>j : any +} +Dependency({}) +>Dependency({}) : any +>Dependency : typeof Dependency +>{} : {} + diff --git a/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt b/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt deleted file mode 100644 index d9104608284..00000000000 --- a/tests/baselines/reference/checkJsFiles_noErrorLocation.errors.txt +++ /dev/null @@ -1,25 +0,0 @@ -tests/cases/compiler/a.js(14,10): error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. - - -==== tests/cases/compiler/a.js (1 errors) ==== - // @ts-check - class A { - constructor() { - - } - foo() { - return 4; - } - } - - class B extends A { - constructor() { - super(); - this.foo = () => 3; - ~~~ -!!! error TS2424: Class 'A' defines instance member function 'foo', but extended class 'B' defines it as instance member property. - } - } - - const i = new B(); - i.foo(); \ No newline at end of file diff --git a/tests/baselines/reference/circularMultipleAssignmentDeclaration.symbols b/tests/baselines/reference/circularMultipleAssignmentDeclaration.symbols new file mode 100644 index 00000000000..c298d31ee7c --- /dev/null +++ b/tests/baselines/reference/circularMultipleAssignmentDeclaration.symbols @@ -0,0 +1,15 @@ +=== tests/cases/conformance/salsa/circularMultipleAssignmentDeclaration.js === +ns.next = ns.next || { shared: {} }; +>ns.next : Symbol(ns.next, Decl(circularMultipleAssignmentDeclaration.js, 0, 0), Decl(circularMultipleAssignmentDeclaration.js, 1, 3)) +>ns : Symbol(ns, Decl(circularMultipleAssignmentDeclaration.js, 0, 0), Decl(circularMultipleAssignmentDeclaration.js, 0, 36)) +>next : Symbol(ns.next, Decl(circularMultipleAssignmentDeclaration.js, 0, 0), Decl(circularMultipleAssignmentDeclaration.js, 1, 3)) +>ns.next : Symbol(ns.next, Decl(circularMultipleAssignmentDeclaration.js, 0, 0), Decl(circularMultipleAssignmentDeclaration.js, 1, 3)) +>ns : Symbol(ns, Decl(circularMultipleAssignmentDeclaration.js, 0, 0), Decl(circularMultipleAssignmentDeclaration.js, 0, 36)) +>next : Symbol(ns.next, Decl(circularMultipleAssignmentDeclaration.js, 0, 0), Decl(circularMultipleAssignmentDeclaration.js, 1, 3)) +>shared : Symbol(shared, Decl(circularMultipleAssignmentDeclaration.js, 0, 22)) + +ns.next.shared.mymethod = {}; +>ns.next : Symbol(ns.next, Decl(circularMultipleAssignmentDeclaration.js, 0, 0), Decl(circularMultipleAssignmentDeclaration.js, 1, 3)) +>ns : Symbol(ns, Decl(circularMultipleAssignmentDeclaration.js, 0, 0), Decl(circularMultipleAssignmentDeclaration.js, 0, 36)) +>next : Symbol(ns.next, Decl(circularMultipleAssignmentDeclaration.js, 0, 0), Decl(circularMultipleAssignmentDeclaration.js, 1, 3)) + diff --git a/tests/baselines/reference/circularMultipleAssignmentDeclaration.types b/tests/baselines/reference/circularMultipleAssignmentDeclaration.types new file mode 100644 index 00000000000..6b5239ed4e4 --- /dev/null +++ b/tests/baselines/reference/circularMultipleAssignmentDeclaration.types @@ -0,0 +1,25 @@ +=== tests/cases/conformance/salsa/circularMultipleAssignmentDeclaration.js === +ns.next = ns.next || { shared: {} }; +>ns.next = ns.next || { shared: {} } : any +>ns.next : any +>ns : typeof ns +>next : any +>ns.next || { shared: {} } : any +>ns.next : any +>ns : typeof ns +>next : any +>{ shared: {} } : { shared: {}; } +>shared : {} +>{} : {} + +ns.next.shared.mymethod = {}; +>ns.next.shared.mymethod = {} : {} +>ns.next.shared.mymethod : any +>ns.next.shared : any +>ns.next : any +>ns : typeof ns +>next : any +>shared : any +>mymethod : any +>{} : {} + diff --git a/tests/baselines/reference/controlFlowOptionalChain.errors.txt b/tests/baselines/reference/controlFlowOptionalChain.errors.txt index ce46b232b3d..ee77494d1c8 100644 --- a/tests/baselines/reference/controlFlowOptionalChain.errors.txt +++ b/tests/baselines/reference/controlFlowOptionalChain.errors.txt @@ -6,7 +6,6 @@ tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(35,5): error TS2 tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(39,1): error TS2722: Cannot invoke an object which is possibly 'undefined'. tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(52,5): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(57,1): error TS2532: Object is possibly 'undefined'. -tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(62,5): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(68,5): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(72,1): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(83,5): error TS2532: Object is possibly 'undefined'. @@ -20,9 +19,41 @@ tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(112,1): error TS tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(130,5): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(134,1): error TS2532: Object is possibly 'undefined'. tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(153,9): error TS2775: Assertions require every name in the call target to be declared with an explicit type annotation. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(208,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(211,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(214,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(217,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(220,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(223,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(238,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(241,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(244,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(271,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(274,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(277,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(307,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(310,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(319,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(322,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(331,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(340,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(343,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(352,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(391,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(394,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(403,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(406,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(415,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(424,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(427,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(436,9): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(471,13): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(474,13): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(488,13): error TS2532: Object is possibly 'undefined'. +tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(491,13): error TS2532: Object is possibly 'undefined'. -==== tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts (22 errors) ==== +==== tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts (53 errors) ==== // assignments in shortcutting chain declare const o: undefined | { [key: string]: any; @@ -99,10 +130,8 @@ tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(153,9): error TS declare const o3: { x: 1, y: string } | { x: 2, y: number } | undefined; if (o3?.x === 1) { - o3; // TODO: should be `{ x: y, y: string }` - o3.x; // TODO: should not be an error. - ~~ -!!! error TS2532: Object is possibly 'undefined'. + o3; + o3.x; o3?.x; } else { @@ -227,4 +256,435 @@ tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts(153,9): error TS x; } } + + type Thing = { foo: string | number, bar(): number, baz: object }; + + function f10(o: Thing | undefined, value: number) { + if (o?.foo === value) { + o.foo; + } + if (o?.["foo"] === value) { + o["foo"]; + } + if (o?.bar() === value) { + o.bar; + } + if (o?.foo == value) { + o.foo; + } + if (o?.["foo"] == value) { + o["foo"]; + } + if (o?.bar() == value) { + o.bar; + } + } + + function f11(o: Thing | null, value: number) { + if (o?.foo === value) { + o.foo; + } + if (o?.["foo"] === value) { + o["foo"]; + } + if (o?.bar() === value) { + o.bar; + } + if (o?.foo == value) { + o.foo; + } + if (o?.["foo"] == value) { + o["foo"]; + } + if (o?.bar() == value) { + o.bar; + } + } + + function f12(o: Thing | undefined, value: number | undefined) { + if (o?.foo === value) { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.["foo"] === value) { + o["foo"]; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.bar() === value) { + o.bar; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.foo == value) { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.["foo"] == value) { + o["foo"]; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.bar() == value) { + o.bar; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + } + + function f12a(o: Thing | undefined, value: number | null) { + if (o?.foo === value) { + o.foo; + } + if (o?.["foo"] === value) { + o["foo"]; + } + if (o?.bar() === value) { + o.bar; + } + if (o?.foo == value) { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.["foo"] == value) { + o["foo"]; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.bar() == value) { + o.bar; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + } + + function f13(o: Thing | undefined) { + if (o?.foo !== undefined) { + o.foo; + } + if (o?.["foo"] !== undefined) { + o["foo"]; + } + if (o?.bar() !== undefined) { + o.bar; + } + if (o?.foo != undefined) { + o.foo; + } + if (o?.["foo"] != undefined) { + o["foo"]; + } + if (o?.bar() != undefined) { + o.bar; + } + } + + function f13a(o: Thing | undefined) { + if (o?.foo !== null) { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.["foo"] !== null) { + o["foo"]; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.bar() !== null) { + o.bar; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.foo != null) { + o.foo; + } + if (o?.["foo"] != null) { + o["foo"]; + } + if (o?.bar() != null) { + o.bar; + } + } + + function f14(o: Thing | null) { + if (o?.foo !== undefined) { + o.foo; + } + if (o?.["foo"] !== undefined) { + o["foo"]; + } + if (o?.bar() !== undefined) { + o.bar; + } + } + + function f15(o: Thing | undefined, value: number) { + if (o?.foo === value) { + o.foo; + } + else { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.foo !== value) { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + else { + o.foo; + } + if (o?.foo == value) { + o.foo; + } + else { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.foo != value) { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + else { + o.foo; + } + } + + function f16(o: Thing | undefined) { + if (o?.foo === undefined) { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + else { + o.foo; + } + if (o?.foo !== undefined) { + o.foo; + } + else { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (o?.foo == undefined) { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + else { + o.foo; + } + if (o?.foo != undefined) { + o.foo; + } + else { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + } + + function f20(o: Thing | undefined) { + if (typeof o?.foo === "number") { + o.foo; + } + if (typeof o?.["foo"] === "number") { + o["foo"]; + } + if (typeof o?.bar() === "number") { + o.bar; + } + if (o?.baz instanceof Error) { + o.baz; + } + } + + function f21(o: Thing | null) { + if (typeof o?.foo === "number") { + o.foo; + } + if (typeof o?.["foo"] === "number") { + o["foo"]; + } + if (typeof o?.bar() === "number") { + o.bar; + } + if (o?.baz instanceof Error) { + o.baz; + } + } + + function f22(o: Thing | undefined) { + if (typeof o?.foo === "number") { + o.foo; + } + else { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (typeof o?.foo !== "number") { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + else { + o.foo; + } + if (typeof o?.foo == "number") { + o.foo; + } + else { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (typeof o?.foo != "number") { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + else { + o.foo; + } + } + + function f23(o: Thing | undefined) { + if (typeof o?.foo === "undefined") { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + else { + o.foo; + } + if (typeof o?.foo !== "undefined") { + o.foo; + } + else { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + if (typeof o?.foo == "undefined") { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + else { + o.foo; + } + if (typeof o?.foo != "undefined") { + o.foo; + } + else { + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + } + } + + declare function assert(x: unknown): asserts x; + declare function assertNonNull(x: T): asserts x is NonNullable; + + function f30(o: Thing | undefined) { + if (!!true) { + assert(o?.foo); + o.foo; + } + if (!!true) { + assert(o?.foo === 42); + o.foo; + } + if (!!true) { + assert(typeof o?.foo === "number"); + o.foo; + } + if (!!true) { + assertNonNull(o?.foo); + o.foo; + } + } + + function f40(o: Thing | undefined) { + switch (o?.foo) { + case "abc": + o.foo; + break; + case 42: + o.foo; + break; + case undefined: + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + break; + default: + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + break; + } + } + + function f41(o: Thing | undefined) { + switch (typeof o?.foo) { + case "string": + o.foo; + break; + case "number": + o.foo; + break; + case "undefined": + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + break; + default: + o.foo; // Error + ~ +!!! error TS2532: Object is possibly 'undefined'. + break; + } + } + + // Repros from #34570 + + type Shape = + | { type: 'rectangle', width: number, height: number } + | { type: 'circle', radius: number } + + function getArea(shape?: Shape) { + switch (shape?.type) { + case 'circle': + return Math.PI * shape.radius ** 2 + case 'rectangle': + return shape.width * shape.height + default: + return 0 + } + } + + type Feature = { + id: string; + geometry?: { + type: string; + coordinates: number[]; + }; + }; + + + function extractCoordinates(f: Feature): number[] { + if (f.geometry?.type !== 'test') { + return []; + } + return f.geometry.coordinates; + } \ No newline at end of file diff --git a/tests/baselines/reference/controlFlowOptionalChain.js b/tests/baselines/reference/controlFlowOptionalChain.js index 58a2873f93a..3bb2bab1c0d 100644 --- a/tests/baselines/reference/controlFlowOptionalChain.js +++ b/tests/baselines/reference/controlFlowOptionalChain.js @@ -59,8 +59,8 @@ o2.f; declare const o3: { x: 1, y: string } | { x: 2, y: number } | undefined; if (o3?.x === 1) { - o3; // TODO: should be `{ x: y, y: string }` - o3.x; // TODO: should not be an error. + o3; + o3.x; o3?.x; } else { @@ -159,6 +159,373 @@ function f01(x: unknown) { x; } } + +type Thing = { foo: string | number, bar(): number, baz: object }; + +function f10(o: Thing | undefined, value: number) { + if (o?.foo === value) { + o.foo; + } + if (o?.["foo"] === value) { + o["foo"]; + } + if (o?.bar() === value) { + o.bar; + } + if (o?.foo == value) { + o.foo; + } + if (o?.["foo"] == value) { + o["foo"]; + } + if (o?.bar() == value) { + o.bar; + } +} + +function f11(o: Thing | null, value: number) { + if (o?.foo === value) { + o.foo; + } + if (o?.["foo"] === value) { + o["foo"]; + } + if (o?.bar() === value) { + o.bar; + } + if (o?.foo == value) { + o.foo; + } + if (o?.["foo"] == value) { + o["foo"]; + } + if (o?.bar() == value) { + o.bar; + } +} + +function f12(o: Thing | undefined, value: number | undefined) { + if (o?.foo === value) { + o.foo; // Error + } + if (o?.["foo"] === value) { + o["foo"]; // Error + } + if (o?.bar() === value) { + o.bar; // Error + } + if (o?.foo == value) { + o.foo; // Error + } + if (o?.["foo"] == value) { + o["foo"]; // Error + } + if (o?.bar() == value) { + o.bar; // Error + } +} + +function f12a(o: Thing | undefined, value: number | null) { + if (o?.foo === value) { + o.foo; + } + if (o?.["foo"] === value) { + o["foo"]; + } + if (o?.bar() === value) { + o.bar; + } + if (o?.foo == value) { + o.foo; // Error + } + if (o?.["foo"] == value) { + o["foo"]; // Error + } + if (o?.bar() == value) { + o.bar; // Error + } +} + +function f13(o: Thing | undefined) { + if (o?.foo !== undefined) { + o.foo; + } + if (o?.["foo"] !== undefined) { + o["foo"]; + } + if (o?.bar() !== undefined) { + o.bar; + } + if (o?.foo != undefined) { + o.foo; + } + if (o?.["foo"] != undefined) { + o["foo"]; + } + if (o?.bar() != undefined) { + o.bar; + } +} + +function f13a(o: Thing | undefined) { + if (o?.foo !== null) { + o.foo; // Error + } + if (o?.["foo"] !== null) { + o["foo"]; // Error + } + if (o?.bar() !== null) { + o.bar; // Error + } + if (o?.foo != null) { + o.foo; + } + if (o?.["foo"] != null) { + o["foo"]; + } + if (o?.bar() != null) { + o.bar; + } +} + +function f14(o: Thing | null) { + if (o?.foo !== undefined) { + o.foo; + } + if (o?.["foo"] !== undefined) { + o["foo"]; + } + if (o?.bar() !== undefined) { + o.bar; + } +} + +function f15(o: Thing | undefined, value: number) { + if (o?.foo === value) { + o.foo; + } + else { + o.foo; // Error + } + if (o?.foo !== value) { + o.foo; // Error + } + else { + o.foo; + } + if (o?.foo == value) { + o.foo; + } + else { + o.foo; // Error + } + if (o?.foo != value) { + o.foo; // Error + } + else { + o.foo; + } +} + +function f16(o: Thing | undefined) { + if (o?.foo === undefined) { + o.foo; // Error + } + else { + o.foo; + } + if (o?.foo !== undefined) { + o.foo; + } + else { + o.foo; // Error + } + if (o?.foo == undefined) { + o.foo; // Error + } + else { + o.foo; + } + if (o?.foo != undefined) { + o.foo; + } + else { + o.foo; // Error + } +} + +function f20(o: Thing | undefined) { + if (typeof o?.foo === "number") { + o.foo; + } + if (typeof o?.["foo"] === "number") { + o["foo"]; + } + if (typeof o?.bar() === "number") { + o.bar; + } + if (o?.baz instanceof Error) { + o.baz; + } +} + +function f21(o: Thing | null) { + if (typeof o?.foo === "number") { + o.foo; + } + if (typeof o?.["foo"] === "number") { + o["foo"]; + } + if (typeof o?.bar() === "number") { + o.bar; + } + if (o?.baz instanceof Error) { + o.baz; + } +} + +function f22(o: Thing | undefined) { + if (typeof o?.foo === "number") { + o.foo; + } + else { + o.foo; // Error + } + if (typeof o?.foo !== "number") { + o.foo; // Error + } + else { + o.foo; + } + if (typeof o?.foo == "number") { + o.foo; + } + else { + o.foo; // Error + } + if (typeof o?.foo != "number") { + o.foo; // Error + } + else { + o.foo; + } +} + +function f23(o: Thing | undefined) { + if (typeof o?.foo === "undefined") { + o.foo; // Error + } + else { + o.foo; + } + if (typeof o?.foo !== "undefined") { + o.foo; + } + else { + o.foo; // Error + } + if (typeof o?.foo == "undefined") { + o.foo; // Error + } + else { + o.foo; + } + if (typeof o?.foo != "undefined") { + o.foo; + } + else { + o.foo; // Error + } +} + +declare function assert(x: unknown): asserts x; +declare function assertNonNull(x: T): asserts x is NonNullable; + +function f30(o: Thing | undefined) { + if (!!true) { + assert(o?.foo); + o.foo; + } + if (!!true) { + assert(o?.foo === 42); + o.foo; + } + if (!!true) { + assert(typeof o?.foo === "number"); + o.foo; + } + if (!!true) { + assertNonNull(o?.foo); + o.foo; + } +} + +function f40(o: Thing | undefined) { + switch (o?.foo) { + case "abc": + o.foo; + break; + case 42: + o.foo; + break; + case undefined: + o.foo; // Error + break; + default: + o.foo; // Error + break; + } +} + +function f41(o: Thing | undefined) { + switch (typeof o?.foo) { + case "string": + o.foo; + break; + case "number": + o.foo; + break; + case "undefined": + o.foo; // Error + break; + default: + o.foo; // Error + break; + } +} + +// Repros from #34570 + +type Shape = + | { type: 'rectangle', width: number, height: number } + | { type: 'circle', radius: number } + +function getArea(shape?: Shape) { + switch (shape?.type) { + case 'circle': + return Math.PI * shape.radius ** 2 + case 'rectangle': + return shape.width * shape.height + default: + return 0 + } +} + +type Feature = { + id: string; + geometry?: { + type: string; + coordinates: number[]; + }; +}; + + +function extractCoordinates(f: Feature): number[] { + if (f.geometry?.type !== 'test') { + return []; + } + return f.geometry.coordinates; +} //// [controlFlowOptionalChain.js] @@ -206,8 +573,8 @@ o2; (_k = o2) === null || _k === void 0 ? void 0 : _k.f; o2.f; if (((_l = o3) === null || _l === void 0 ? void 0 : _l.x) === 1) { - o3; // TODO: should be `{ x: y, y: string }` - o3.x; // TODO: should not be an error. + o3; + o3.x; (_m = o3) === null || _m === void 0 ? void 0 : _m.x; } else { @@ -286,3 +653,350 @@ function f01(x) { x; } } +function f10(o, value) { + var _a, _b, _c, _d, _e, _f; + if (((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === value) { + o.foo; + } + if (((_b = o) === null || _b === void 0 ? void 0 : _b["foo"]) === value) { + o["foo"]; + } + if (((_c = o) === null || _c === void 0 ? void 0 : _c.bar()) === value) { + o.bar; + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.foo) == value) { + o.foo; + } + if (((_e = o) === null || _e === void 0 ? void 0 : _e["foo"]) == value) { + o["foo"]; + } + if (((_f = o) === null || _f === void 0 ? void 0 : _f.bar()) == value) { + o.bar; + } +} +function f11(o, value) { + var _a, _b, _c, _d, _e, _f; + if (((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === value) { + o.foo; + } + if (((_b = o) === null || _b === void 0 ? void 0 : _b["foo"]) === value) { + o["foo"]; + } + if (((_c = o) === null || _c === void 0 ? void 0 : _c.bar()) === value) { + o.bar; + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.foo) == value) { + o.foo; + } + if (((_e = o) === null || _e === void 0 ? void 0 : _e["foo"]) == value) { + o["foo"]; + } + if (((_f = o) === null || _f === void 0 ? void 0 : _f.bar()) == value) { + o.bar; + } +} +function f12(o, value) { + var _a, _b, _c, _d, _e, _f; + if (((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === value) { + o.foo; // Error + } + if (((_b = o) === null || _b === void 0 ? void 0 : _b["foo"]) === value) { + o["foo"]; // Error + } + if (((_c = o) === null || _c === void 0 ? void 0 : _c.bar()) === value) { + o.bar; // Error + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.foo) == value) { + o.foo; // Error + } + if (((_e = o) === null || _e === void 0 ? void 0 : _e["foo"]) == value) { + o["foo"]; // Error + } + if (((_f = o) === null || _f === void 0 ? void 0 : _f.bar()) == value) { + o.bar; // Error + } +} +function f12a(o, value) { + var _a, _b, _c, _d, _e, _f; + if (((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === value) { + o.foo; + } + if (((_b = o) === null || _b === void 0 ? void 0 : _b["foo"]) === value) { + o["foo"]; + } + if (((_c = o) === null || _c === void 0 ? void 0 : _c.bar()) === value) { + o.bar; + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.foo) == value) { + o.foo; // Error + } + if (((_e = o) === null || _e === void 0 ? void 0 : _e["foo"]) == value) { + o["foo"]; // Error + } + if (((_f = o) === null || _f === void 0 ? void 0 : _f.bar()) == value) { + o.bar; // Error + } +} +function f13(o) { + var _a, _b, _c, _d, _e, _f; + if (((_a = o) === null || _a === void 0 ? void 0 : _a.foo) !== undefined) { + o.foo; + } + if (((_b = o) === null || _b === void 0 ? void 0 : _b["foo"]) !== undefined) { + o["foo"]; + } + if (((_c = o) === null || _c === void 0 ? void 0 : _c.bar()) !== undefined) { + o.bar; + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.foo) != undefined) { + o.foo; + } + if (((_e = o) === null || _e === void 0 ? void 0 : _e["foo"]) != undefined) { + o["foo"]; + } + if (((_f = o) === null || _f === void 0 ? void 0 : _f.bar()) != undefined) { + o.bar; + } +} +function f13a(o) { + var _a, _b, _c, _d, _e, _f; + if (((_a = o) === null || _a === void 0 ? void 0 : _a.foo) !== null) { + o.foo; // Error + } + if (((_b = o) === null || _b === void 0 ? void 0 : _b["foo"]) !== null) { + o["foo"]; // Error + } + if (((_c = o) === null || _c === void 0 ? void 0 : _c.bar()) !== null) { + o.bar; // Error + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.foo) != null) { + o.foo; + } + if (((_e = o) === null || _e === void 0 ? void 0 : _e["foo"]) != null) { + o["foo"]; + } + if (((_f = o) === null || _f === void 0 ? void 0 : _f.bar()) != null) { + o.bar; + } +} +function f14(o) { + var _a, _b, _c; + if (((_a = o) === null || _a === void 0 ? void 0 : _a.foo) !== undefined) { + o.foo; + } + if (((_b = o) === null || _b === void 0 ? void 0 : _b["foo"]) !== undefined) { + o["foo"]; + } + if (((_c = o) === null || _c === void 0 ? void 0 : _c.bar()) !== undefined) { + o.bar; + } +} +function f15(o, value) { + var _a, _b, _c, _d; + if (((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === value) { + o.foo; + } + else { + o.foo; // Error + } + if (((_b = o) === null || _b === void 0 ? void 0 : _b.foo) !== value) { + o.foo; // Error + } + else { + o.foo; + } + if (((_c = o) === null || _c === void 0 ? void 0 : _c.foo) == value) { + o.foo; + } + else { + o.foo; // Error + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.foo) != value) { + o.foo; // Error + } + else { + o.foo; + } +} +function f16(o) { + var _a, _b, _c, _d; + if (((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === undefined) { + o.foo; // Error + } + else { + o.foo; + } + if (((_b = o) === null || _b === void 0 ? void 0 : _b.foo) !== undefined) { + o.foo; + } + else { + o.foo; // Error + } + if (((_c = o) === null || _c === void 0 ? void 0 : _c.foo) == undefined) { + o.foo; // Error + } + else { + o.foo; + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.foo) != undefined) { + o.foo; + } + else { + o.foo; // Error + } +} +function f20(o) { + var _a, _b, _c, _d; + if (typeof ((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === "number") { + o.foo; + } + if (typeof ((_b = o) === null || _b === void 0 ? void 0 : _b["foo"]) === "number") { + o["foo"]; + } + if (typeof ((_c = o) === null || _c === void 0 ? void 0 : _c.bar()) === "number") { + o.bar; + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.baz) instanceof Error) { + o.baz; + } +} +function f21(o) { + var _a, _b, _c, _d; + if (typeof ((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === "number") { + o.foo; + } + if (typeof ((_b = o) === null || _b === void 0 ? void 0 : _b["foo"]) === "number") { + o["foo"]; + } + if (typeof ((_c = o) === null || _c === void 0 ? void 0 : _c.bar()) === "number") { + o.bar; + } + if (((_d = o) === null || _d === void 0 ? void 0 : _d.baz) instanceof Error) { + o.baz; + } +} +function f22(o) { + var _a, _b, _c, _d; + if (typeof ((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === "number") { + o.foo; + } + else { + o.foo; // Error + } + if (typeof ((_b = o) === null || _b === void 0 ? void 0 : _b.foo) !== "number") { + o.foo; // Error + } + else { + o.foo; + } + if (typeof ((_c = o) === null || _c === void 0 ? void 0 : _c.foo) == "number") { + o.foo; + } + else { + o.foo; // Error + } + if (typeof ((_d = o) === null || _d === void 0 ? void 0 : _d.foo) != "number") { + o.foo; // Error + } + else { + o.foo; + } +} +function f23(o) { + var _a, _b, _c, _d; + if (typeof ((_a = o) === null || _a === void 0 ? void 0 : _a.foo) === "undefined") { + o.foo; // Error + } + else { + o.foo; + } + if (typeof ((_b = o) === null || _b === void 0 ? void 0 : _b.foo) !== "undefined") { + o.foo; + } + else { + o.foo; // Error + } + if (typeof ((_c = o) === null || _c === void 0 ? void 0 : _c.foo) == "undefined") { + o.foo; // Error + } + else { + o.foo; + } + if (typeof ((_d = o) === null || _d === void 0 ? void 0 : _d.foo) != "undefined") { + o.foo; + } + else { + o.foo; // Error + } +} +function f30(o) { + var _a, _b, _c, _d; + if (!!true) { + assert((_a = o) === null || _a === void 0 ? void 0 : _a.foo); + o.foo; + } + if (!!true) { + assert(((_b = o) === null || _b === void 0 ? void 0 : _b.foo) === 42); + o.foo; + } + if (!!true) { + assert(typeof ((_c = o) === null || _c === void 0 ? void 0 : _c.foo) === "number"); + o.foo; + } + if (!!true) { + assertNonNull((_d = o) === null || _d === void 0 ? void 0 : _d.foo); + o.foo; + } +} +function f40(o) { + var _a; + switch ((_a = o) === null || _a === void 0 ? void 0 : _a.foo) { + case "abc": + o.foo; + break; + case 42: + o.foo; + break; + case undefined: + o.foo; // Error + break; + default: + o.foo; // Error + break; + } +} +function f41(o) { + var _a; + switch (typeof ((_a = o) === null || _a === void 0 ? void 0 : _a.foo)) { + case "string": + o.foo; + break; + case "number": + o.foo; + break; + case "undefined": + o.foo; // Error + break; + default: + o.foo; // Error + break; + } +} +function getArea(shape) { + var _a; + switch ((_a = shape) === null || _a === void 0 ? void 0 : _a.type) { + case 'circle': + return Math.PI * Math.pow(shape.radius, 2); + case 'rectangle': + return shape.width * shape.height; + default: + return 0; + } +} +function extractCoordinates(f) { + var _a; + if (((_a = f.geometry) === null || _a === void 0 ? void 0 : _a.type) !== 'test') { + return []; + } + return f.geometry.coordinates; +} diff --git a/tests/baselines/reference/controlFlowOptionalChain.symbols b/tests/baselines/reference/controlFlowOptionalChain.symbols index 21f1de2a410..cac0899cc89 100644 --- a/tests/baselines/reference/controlFlowOptionalChain.symbols +++ b/tests/baselines/reference/controlFlowOptionalChain.symbols @@ -182,18 +182,18 @@ if (o3?.x === 1) { >o3 : Symbol(o3, Decl(controlFlowOptionalChain.ts, 58, 13)) >x : Symbol(x, Decl(controlFlowOptionalChain.ts, 58, 19), Decl(controlFlowOptionalChain.ts, 58, 41)) - o3; // TODO: should be `{ x: y, y: string }` + o3; >o3 : Symbol(o3, Decl(controlFlowOptionalChain.ts, 58, 13)) - o3.x; // TODO: should not be an error. ->o3.x : Symbol(x, Decl(controlFlowOptionalChain.ts, 58, 19), Decl(controlFlowOptionalChain.ts, 58, 41)) + o3.x; +>o3.x : Symbol(x, Decl(controlFlowOptionalChain.ts, 58, 19)) >o3 : Symbol(o3, Decl(controlFlowOptionalChain.ts, 58, 13)) ->x : Symbol(x, Decl(controlFlowOptionalChain.ts, 58, 19), Decl(controlFlowOptionalChain.ts, 58, 41)) +>x : Symbol(x, Decl(controlFlowOptionalChain.ts, 58, 19)) o3?.x; ->o3?.x : Symbol(x, Decl(controlFlowOptionalChain.ts, 58, 19), Decl(controlFlowOptionalChain.ts, 58, 41)) +>o3?.x : Symbol(x, Decl(controlFlowOptionalChain.ts, 58, 19)) >o3 : Symbol(o3, Decl(controlFlowOptionalChain.ts, 58, 13)) ->x : Symbol(x, Decl(controlFlowOptionalChain.ts, 58, 19), Decl(controlFlowOptionalChain.ts, 58, 41)) +>x : Symbol(x, Decl(controlFlowOptionalChain.ts, 58, 19)) } else { o3; @@ -600,3 +600,1066 @@ function f01(x: unknown) { } } +type Thing = { foo: string | number, bar(): number, baz: object }; +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>baz : Symbol(baz, Decl(controlFlowOptionalChain.ts, 161, 51)) + +function f10(o: Thing | undefined, value: number) { +>f10 : Symbol(f10, Decl(controlFlowOptionalChain.ts, 161, 66)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 163, 34)) + + if (o?.foo === value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 163, 34)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] === value) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 163, 34)) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.bar() === value) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 163, 34)) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } + if (o?.foo == value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 163, 34)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] == value) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 163, 34)) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.bar() == value) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 163, 34)) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 163, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } +} + +function f11(o: Thing | null, value: number) { +>f11 : Symbol(f11, Decl(controlFlowOptionalChain.ts, 182, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 184, 29)) + + if (o?.foo === value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 184, 29)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] === value) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 184, 29)) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.bar() === value) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 184, 29)) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } + if (o?.foo == value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 184, 29)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] == value) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 184, 29)) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.bar() == value) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 184, 29)) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 184, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } +} + +function f12(o: Thing | undefined, value: number | undefined) { +>f12 : Symbol(f12, Decl(controlFlowOptionalChain.ts, 203, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 205, 34)) + + if (o?.foo === value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 205, 34)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] === value) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 205, 34)) + + o["foo"]; // Error +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) + } + if (o?.bar() === value) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 205, 34)) + + o.bar; // Error +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } + if (o?.foo == value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 205, 34)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] == value) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 205, 34)) + + o["foo"]; // Error +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) + } + if (o?.bar() == value) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 205, 34)) + + o.bar; // Error +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 205, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } +} + +function f12a(o: Thing | undefined, value: number | null) { +>f12a : Symbol(f12a, Decl(controlFlowOptionalChain.ts, 224, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 226, 35)) + + if (o?.foo === value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 226, 35)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] === value) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 226, 35)) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.bar() === value) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 226, 35)) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } + if (o?.foo == value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 226, 35)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] == value) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 226, 35)) + + o["foo"]; // Error +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) + } + if (o?.bar() == value) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 226, 35)) + + o.bar; // Error +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 226, 14)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } +} + +function f13(o: Thing | undefined) { +>f13 : Symbol(f13, Decl(controlFlowOptionalChain.ts, 245, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + if (o?.foo !== undefined) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>undefined : Symbol(undefined) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] !== undefined) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>undefined : Symbol(undefined) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.bar() !== undefined) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>undefined : Symbol(undefined) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } + if (o?.foo != undefined) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>undefined : Symbol(undefined) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] != undefined) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>undefined : Symbol(undefined) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.bar() != undefined) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>undefined : Symbol(undefined) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 247, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } +} + +function f13a(o: Thing | undefined) { +>f13a : Symbol(f13a, Decl(controlFlowOptionalChain.ts, 266, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + if (o?.foo !== null) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] !== null) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) + + o["foo"]; // Error +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) + } + if (o?.bar() !== null) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + + o.bar; // Error +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } + if (o?.foo != null) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] != null) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.bar() != null) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 268, 14)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } +} + +function f14(o: Thing | null) { +>f14 : Symbol(f14, Decl(controlFlowOptionalChain.ts, 287, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 289, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + if (o?.foo !== undefined) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 289, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>undefined : Symbol(undefined) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 289, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.["foo"] !== undefined) { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 289, 13)) +>undefined : Symbol(undefined) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 289, 13)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.bar() !== undefined) { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 289, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>undefined : Symbol(undefined) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 289, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } +} + +function f15(o: Thing | undefined, value: number) { +>f15 : Symbol(f15, Decl(controlFlowOptionalChain.ts, 299, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 301, 34)) + + if (o?.foo === value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 301, 34)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.foo !== value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 301, 34)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.foo == value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 301, 34)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.foo != value) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>value : Symbol(value, Decl(controlFlowOptionalChain.ts, 301, 34)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 301, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } +} + +function f16(o: Thing | undefined) { +>f16 : Symbol(f16, Decl(controlFlowOptionalChain.ts, 326, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + if (o?.foo === undefined) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>undefined : Symbol(undefined) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.foo !== undefined) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>undefined : Symbol(undefined) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.foo == undefined) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>undefined : Symbol(undefined) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (o?.foo != undefined) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>undefined : Symbol(undefined) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 328, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } +} + +function f20(o: Thing | undefined) { +>f20 : Symbol(f20, Decl(controlFlowOptionalChain.ts, 353, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 355, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + if (typeof o?.foo === "number") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 355, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 355, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.["foo"] === "number") { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 355, 13)) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 355, 13)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.bar() === "number") { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 355, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 355, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } + if (o?.baz instanceof Error) { +>o?.baz : Symbol(baz, Decl(controlFlowOptionalChain.ts, 161, 51)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 355, 13)) +>baz : Symbol(baz, Decl(controlFlowOptionalChain.ts, 161, 51)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + + o.baz; +>o.baz : Symbol(baz, Decl(controlFlowOptionalChain.ts, 161, 51)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 355, 13)) +>baz : Symbol(baz, Decl(controlFlowOptionalChain.ts, 161, 51)) + } +} + +function f21(o: Thing | null) { +>f21 : Symbol(f21, Decl(controlFlowOptionalChain.ts, 368, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 370, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + if (typeof o?.foo === "number") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 370, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 370, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.["foo"] === "number") { +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 370, 13)) + + o["foo"]; +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 370, 13)) +>"foo" : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.bar() === "number") { +>o?.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 370, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + + o.bar; +>o.bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 370, 13)) +>bar : Symbol(bar, Decl(controlFlowOptionalChain.ts, 161, 36)) + } + if (o?.baz instanceof Error) { +>o?.baz : Symbol(baz, Decl(controlFlowOptionalChain.ts, 161, 51)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 370, 13)) +>baz : Symbol(baz, Decl(controlFlowOptionalChain.ts, 161, 51)) +>Error : Symbol(Error, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) + + o.baz; +>o.baz : Symbol(baz, Decl(controlFlowOptionalChain.ts, 161, 51)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 370, 13)) +>baz : Symbol(baz, Decl(controlFlowOptionalChain.ts, 161, 51)) + } +} + +function f22(o: Thing | undefined) { +>f22 : Symbol(f22, Decl(controlFlowOptionalChain.ts, 383, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + if (typeof o?.foo === "number") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.foo !== "number") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.foo == "number") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.foo != "number") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 385, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } +} + +function f23(o: Thing | undefined) { +>f23 : Symbol(f23, Decl(controlFlowOptionalChain.ts, 410, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + if (typeof o?.foo === "undefined") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.foo !== "undefined") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.foo == "undefined") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (typeof o?.foo != "undefined") { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + else { + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 412, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } +} + +declare function assert(x: unknown): asserts x; +>assert : Symbol(assert, Decl(controlFlowOptionalChain.ts, 437, 1)) +>x : Symbol(x, Decl(controlFlowOptionalChain.ts, 439, 24)) +>x : Symbol(x, Decl(controlFlowOptionalChain.ts, 439, 24)) + +declare function assertNonNull(x: T): asserts x is NonNullable; +>assertNonNull : Symbol(assertNonNull, Decl(controlFlowOptionalChain.ts, 439, 47)) +>T : Symbol(T, Decl(controlFlowOptionalChain.ts, 440, 31)) +>x : Symbol(x, Decl(controlFlowOptionalChain.ts, 440, 34)) +>T : Symbol(T, Decl(controlFlowOptionalChain.ts, 440, 31)) +>x : Symbol(x, Decl(controlFlowOptionalChain.ts, 440, 34)) +>NonNullable : Symbol(NonNullable, Decl(lib.es5.d.ts, --, --)) +>T : Symbol(T, Decl(controlFlowOptionalChain.ts, 440, 31)) + +function f30(o: Thing | undefined) { +>f30 : Symbol(f30, Decl(controlFlowOptionalChain.ts, 440, 69)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 442, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + if (!!true) { + assert(o?.foo); +>assert : Symbol(assert, Decl(controlFlowOptionalChain.ts, 437, 1)) +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 442, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 442, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (!!true) { + assert(o?.foo === 42); +>assert : Symbol(assert, Decl(controlFlowOptionalChain.ts, 437, 1)) +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 442, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 442, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (!!true) { + assert(typeof o?.foo === "number"); +>assert : Symbol(assert, Decl(controlFlowOptionalChain.ts, 437, 1)) +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 442, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 442, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } + if (!!true) { + assertNonNull(o?.foo); +>assertNonNull : Symbol(assertNonNull, Decl(controlFlowOptionalChain.ts, 439, 47)) +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 442, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 442, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + } +} + +function f40(o: Thing | undefined) { +>f40 : Symbol(f40, Decl(controlFlowOptionalChain.ts, 459, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 461, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + switch (o?.foo) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 461, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + case "abc": + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 461, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + break; + case 42: + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 461, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + break; + case undefined: +>undefined : Symbol(undefined) + + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 461, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + break; + default: + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 461, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + break; + } +} + +function f41(o: Thing | undefined) { +>f41 : Symbol(f41, Decl(controlFlowOptionalChain.ts, 476, 1)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 478, 13)) +>Thing : Symbol(Thing, Decl(controlFlowOptionalChain.ts, 159, 1)) + + switch (typeof o?.foo) { +>o?.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 478, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + case "string": + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 478, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + break; + case "number": + o.foo; +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 478, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + break; + case "undefined": + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 478, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + break; + default: + o.foo; // Error +>o.foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) +>o : Symbol(o, Decl(controlFlowOptionalChain.ts, 478, 13)) +>foo : Symbol(foo, Decl(controlFlowOptionalChain.ts, 161, 14)) + + break; + } +} + +// Repros from #34570 + +type Shape = +>Shape : Symbol(Shape, Decl(controlFlowOptionalChain.ts, 493, 1)) + + | { type: 'rectangle', width: number, height: number } +>type : Symbol(type, Decl(controlFlowOptionalChain.ts, 498, 7)) +>width : Symbol(width, Decl(controlFlowOptionalChain.ts, 498, 26)) +>height : Symbol(height, Decl(controlFlowOptionalChain.ts, 498, 41)) + + | { type: 'circle', radius: number } +>type : Symbol(type, Decl(controlFlowOptionalChain.ts, 499, 7)) +>radius : Symbol(radius, Decl(controlFlowOptionalChain.ts, 499, 23)) + +function getArea(shape?: Shape) { +>getArea : Symbol(getArea, Decl(controlFlowOptionalChain.ts, 499, 40)) +>shape : Symbol(shape, Decl(controlFlowOptionalChain.ts, 501, 17)) +>Shape : Symbol(Shape, Decl(controlFlowOptionalChain.ts, 493, 1)) + + switch (shape?.type) { +>shape?.type : Symbol(type, Decl(controlFlowOptionalChain.ts, 498, 7), Decl(controlFlowOptionalChain.ts, 499, 7)) +>shape : Symbol(shape, Decl(controlFlowOptionalChain.ts, 501, 17)) +>type : Symbol(type, Decl(controlFlowOptionalChain.ts, 498, 7), Decl(controlFlowOptionalChain.ts, 499, 7)) + + case 'circle': + return Math.PI * shape.radius ** 2 +>Math.PI : Symbol(Math.PI, Decl(lib.es5.d.ts, --, --)) +>Math : Symbol(Math, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>PI : Symbol(Math.PI, Decl(lib.es5.d.ts, --, --)) +>shape.radius : Symbol(radius, Decl(controlFlowOptionalChain.ts, 499, 23)) +>shape : Symbol(shape, Decl(controlFlowOptionalChain.ts, 501, 17)) +>radius : Symbol(radius, Decl(controlFlowOptionalChain.ts, 499, 23)) + + case 'rectangle': + return shape.width * shape.height +>shape.width : Symbol(width, Decl(controlFlowOptionalChain.ts, 498, 26)) +>shape : Symbol(shape, Decl(controlFlowOptionalChain.ts, 501, 17)) +>width : Symbol(width, Decl(controlFlowOptionalChain.ts, 498, 26)) +>shape.height : Symbol(height, Decl(controlFlowOptionalChain.ts, 498, 41)) +>shape : Symbol(shape, Decl(controlFlowOptionalChain.ts, 501, 17)) +>height : Symbol(height, Decl(controlFlowOptionalChain.ts, 498, 41)) + + default: + return 0 + } +} + +type Feature = { +>Feature : Symbol(Feature, Decl(controlFlowOptionalChain.ts, 510, 1)) + + id: string; +>id : Symbol(id, Decl(controlFlowOptionalChain.ts, 512, 16)) + + geometry?: { +>geometry : Symbol(geometry, Decl(controlFlowOptionalChain.ts, 513, 13)) + + type: string; +>type : Symbol(type, Decl(controlFlowOptionalChain.ts, 514, 14)) + + coordinates: number[]; +>coordinates : Symbol(coordinates, Decl(controlFlowOptionalChain.ts, 515, 17)) + + }; +}; + + +function extractCoordinates(f: Feature): number[] { +>extractCoordinates : Symbol(extractCoordinates, Decl(controlFlowOptionalChain.ts, 518, 2)) +>f : Symbol(f, Decl(controlFlowOptionalChain.ts, 521, 28)) +>Feature : Symbol(Feature, Decl(controlFlowOptionalChain.ts, 510, 1)) + + if (f.geometry?.type !== 'test') { +>f.geometry?.type : Symbol(type, Decl(controlFlowOptionalChain.ts, 514, 14)) +>f.geometry : Symbol(geometry, Decl(controlFlowOptionalChain.ts, 513, 13)) +>f : Symbol(f, Decl(controlFlowOptionalChain.ts, 521, 28)) +>geometry : Symbol(geometry, Decl(controlFlowOptionalChain.ts, 513, 13)) +>type : Symbol(type, Decl(controlFlowOptionalChain.ts, 514, 14)) + + return []; + } + return f.geometry.coordinates; +>f.geometry.coordinates : Symbol(coordinates, Decl(controlFlowOptionalChain.ts, 515, 17)) +>f.geometry : Symbol(geometry, Decl(controlFlowOptionalChain.ts, 513, 13)) +>f : Symbol(f, Decl(controlFlowOptionalChain.ts, 521, 28)) +>geometry : Symbol(geometry, Decl(controlFlowOptionalChain.ts, 513, 13)) +>coordinates : Symbol(coordinates, Decl(controlFlowOptionalChain.ts, 515, 17)) +} + diff --git a/tests/baselines/reference/controlFlowOptionalChain.types b/tests/baselines/reference/controlFlowOptionalChain.types index a93c5b0b43f..13dd6cd5fd0 100644 --- a/tests/baselines/reference/controlFlowOptionalChain.types +++ b/tests/baselines/reference/controlFlowOptionalChain.types @@ -208,18 +208,18 @@ if (o3?.x === 1) { >x : 1 | 2 | undefined >1 : 1 - o3; // TODO: should be `{ x: y, y: string }` ->o3 : { x: 1; y: string; } | { x: 2; y: number; } | undefined + o3; +>o3 : { x: 1; y: string; } - o3.x; // TODO: should not be an error. + o3.x; >o3.x : 1 ->o3 : { x: 1; y: string; } | { x: 2; y: number; } | undefined +>o3 : { x: 1; y: string; } >x : 1 o3?.x; ->o3?.x : 1 | undefined ->o3 : { x: 1; y: string; } | { x: 2; y: number; } | undefined ->x : 1 | undefined +>o3?.x : 1 +>o3 : { x: 1; y: string; } +>x : 1 } else { o3; @@ -634,3 +634,1255 @@ function f01(x: unknown) { } } +type Thing = { foo: string | number, bar(): number, baz: object }; +>Thing : Thing +>foo : string | number +>bar : () => number +>baz : object + +function f10(o: Thing | undefined, value: number) { +>f10 : (o: Thing | undefined, value: number) => void +>o : Thing | undefined +>value : number + + if (o?.foo === value) { +>o?.foo === value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number + + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + if (o?.["foo"] === value) { +>o?.["foo"] === value : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>value : number + + o["foo"]; +>o["foo"] : number +>o : Thing +>"foo" : "foo" + } + if (o?.bar() === value) { +>o?.bar() === value : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>value : number + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } + if (o?.foo == value) { +>o?.foo == value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (o?.["foo"] == value) { +>o?.["foo"] == value : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>value : number + + o["foo"]; +>o["foo"] : string | number +>o : Thing +>"foo" : "foo" + } + if (o?.bar() == value) { +>o?.bar() == value : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>value : number + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } +} + +function f11(o: Thing | null, value: number) { +>f11 : (o: Thing | null, value: number) => void +>o : Thing | null +>null : null +>value : number + + if (o?.foo === value) { +>o?.foo === value : boolean +>o?.foo : string | number | undefined +>o : Thing | null +>foo : string | number | undefined +>value : number + + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + if (o?.["foo"] === value) { +>o?.["foo"] === value : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | null +>"foo" : "foo" +>value : number + + o["foo"]; +>o["foo"] : number +>o : Thing +>"foo" : "foo" + } + if (o?.bar() === value) { +>o?.bar() === value : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | null +>bar : (() => number) | undefined +>value : number + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } + if (o?.foo == value) { +>o?.foo == value : boolean +>o?.foo : string | number | undefined +>o : Thing | null +>foo : string | number | undefined +>value : number + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (o?.["foo"] == value) { +>o?.["foo"] == value : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | null +>"foo" : "foo" +>value : number + + o["foo"]; +>o["foo"] : string | number +>o : Thing +>"foo" : "foo" + } + if (o?.bar() == value) { +>o?.bar() == value : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | null +>bar : (() => number) | undefined +>value : number + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } +} + +function f12(o: Thing | undefined, value: number | undefined) { +>f12 : (o: Thing | undefined, value: number | undefined) => void +>o : Thing | undefined +>value : number | undefined + + if (o?.foo === value) { +>o?.foo === value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number | undefined + + o.foo; // Error +>o.foo : number +>o : Thing | undefined +>foo : number + } + if (o?.["foo"] === value) { +>o?.["foo"] === value : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>value : number | undefined + + o["foo"]; // Error +>o["foo"] : number +>o : Thing | undefined +>"foo" : "foo" + } + if (o?.bar() === value) { +>o?.bar() === value : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>value : number | undefined + + o.bar; // Error +>o.bar : () => number +>o : Thing | undefined +>bar : () => number + } + if (o?.foo == value) { +>o?.foo == value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number | undefined + + o.foo; // Error +>o.foo : number +>o : Thing | undefined +>foo : number + } + if (o?.["foo"] == value) { +>o?.["foo"] == value : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>value : number | undefined + + o["foo"]; // Error +>o["foo"] : number +>o : Thing | undefined +>"foo" : "foo" + } + if (o?.bar() == value) { +>o?.bar() == value : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>value : number | undefined + + o.bar; // Error +>o.bar : () => number +>o : Thing | undefined +>bar : () => number + } +} + +function f12a(o: Thing | undefined, value: number | null) { +>f12a : (o: Thing | undefined, value: number | null) => void +>o : Thing | undefined +>value : number | null +>null : null + + if (o?.foo === value) { +>o?.foo === value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number | null + + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + if (o?.["foo"] === value) { +>o?.["foo"] === value : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>value : number | null + + o["foo"]; +>o["foo"] : number +>o : Thing +>"foo" : "foo" + } + if (o?.bar() === value) { +>o?.bar() === value : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>value : number | null + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } + if (o?.foo == value) { +>o?.foo == value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number | null + + o.foo; // Error +>o.foo : number +>o : Thing | undefined +>foo : number + } + if (o?.["foo"] == value) { +>o?.["foo"] == value : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>value : number | null + + o["foo"]; // Error +>o["foo"] : number +>o : Thing | undefined +>"foo" : "foo" + } + if (o?.bar() == value) { +>o?.bar() == value : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>value : number | null + + o.bar; // Error +>o.bar : () => number +>o : Thing | undefined +>bar : () => number + } +} + +function f13(o: Thing | undefined) { +>f13 : (o: Thing | undefined) => void +>o : Thing | undefined + + if (o?.foo !== undefined) { +>o?.foo !== undefined : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>undefined : undefined + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (o?.["foo"] !== undefined) { +>o?.["foo"] !== undefined : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>undefined : undefined + + o["foo"]; +>o["foo"] : string | number +>o : Thing +>"foo" : "foo" + } + if (o?.bar() !== undefined) { +>o?.bar() !== undefined : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>undefined : undefined + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } + if (o?.foo != undefined) { +>o?.foo != undefined : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>undefined : undefined + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (o?.["foo"] != undefined) { +>o?.["foo"] != undefined : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>undefined : undefined + + o["foo"]; +>o["foo"] : string | number +>o : Thing +>"foo" : "foo" + } + if (o?.bar() != undefined) { +>o?.bar() != undefined : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>undefined : undefined + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } +} + +function f13a(o: Thing | undefined) { +>f13a : (o: Thing | undefined) => void +>o : Thing | undefined + + if (o?.foo !== null) { +>o?.foo !== null : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>null : null + + o.foo; // Error +>o.foo : string | number +>o : Thing | undefined +>foo : string | number + } + if (o?.["foo"] !== null) { +>o?.["foo"] !== null : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>null : null + + o["foo"]; // Error +>o["foo"] : string | number +>o : Thing | undefined +>"foo" : "foo" + } + if (o?.bar() !== null) { +>o?.bar() !== null : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>null : null + + o.bar; // Error +>o.bar : () => number +>o : Thing | undefined +>bar : () => number + } + if (o?.foo != null) { +>o?.foo != null : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>null : null + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (o?.["foo"] != null) { +>o?.["foo"] != null : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>null : null + + o["foo"]; +>o["foo"] : string | number +>o : Thing +>"foo" : "foo" + } + if (o?.bar() != null) { +>o?.bar() != null : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>null : null + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } +} + +function f14(o: Thing | null) { +>f14 : (o: Thing | null) => void +>o : Thing | null +>null : null + + if (o?.foo !== undefined) { +>o?.foo !== undefined : boolean +>o?.foo : string | number | undefined +>o : Thing | null +>foo : string | number | undefined +>undefined : undefined + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (o?.["foo"] !== undefined) { +>o?.["foo"] !== undefined : boolean +>o?.["foo"] : string | number | undefined +>o : Thing | null +>"foo" : "foo" +>undefined : undefined + + o["foo"]; +>o["foo"] : string | number +>o : Thing +>"foo" : "foo" + } + if (o?.bar() !== undefined) { +>o?.bar() !== undefined : boolean +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | null +>bar : (() => number) | undefined +>undefined : undefined + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } +} + +function f15(o: Thing | undefined, value: number) { +>f15 : (o: Thing | undefined, value: number) => void +>o : Thing | undefined +>value : number + + if (o?.foo === value) { +>o?.foo === value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number + + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + else { + o.foo; // Error +>o.foo : string | number +>o : Thing | undefined +>foo : string | number + } + if (o?.foo !== value) { +>o?.foo !== value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number + + o.foo; // Error +>o.foo : string | number +>o : Thing | undefined +>foo : string | number + } + else { + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + if (o?.foo == value) { +>o?.foo == value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + else { + o.foo; // Error +>o.foo : string | number +>o : Thing | undefined +>foo : string | number + } + if (o?.foo != value) { +>o?.foo != value : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>value : number + + o.foo; // Error +>o.foo : string | number +>o : Thing | undefined +>foo : string | number + } + else { + o.foo; +>o.foo : number +>o : Thing +>foo : number + } +} + +function f16(o: Thing | undefined) { +>f16 : (o: Thing | undefined) => void +>o : Thing | undefined + + if (o?.foo === undefined) { +>o?.foo === undefined : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>undefined : undefined + + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + } + else { + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (o?.foo !== undefined) { +>o?.foo !== undefined : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>undefined : undefined + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + else { + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + } + if (o?.foo == undefined) { +>o?.foo == undefined : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>undefined : undefined + + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + } + else { + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (o?.foo != undefined) { +>o?.foo != undefined : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>undefined : undefined + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + else { + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + } +} + +function f20(o: Thing | undefined) { +>f20 : (o: Thing | undefined) => void +>o : Thing | undefined + + if (typeof o?.foo === "number") { +>typeof o?.foo === "number" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"number" : "number" + + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + if (typeof o?.["foo"] === "number") { +>typeof o?.["foo"] === "number" : boolean +>typeof o?.["foo"] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.["foo"] : string | number | undefined +>o : Thing | undefined +>"foo" : "foo" +>"number" : "number" + + o["foo"]; +>o["foo"] : number +>o : Thing +>"foo" : "foo" + } + if (typeof o?.bar() === "number") { +>typeof o?.bar() === "number" : boolean +>typeof o?.bar() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | undefined +>bar : (() => number) | undefined +>"number" : "number" + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } + if (o?.baz instanceof Error) { +>o?.baz instanceof Error : boolean +>o?.baz : object | undefined +>o : Thing | undefined +>baz : object | undefined +>Error : ErrorConstructor + + o.baz; +>o.baz : Error +>o : Thing +>baz : Error + } +} + +function f21(o: Thing | null) { +>f21 : (o: Thing | null) => void +>o : Thing | null +>null : null + + if (typeof o?.foo === "number") { +>typeof o?.foo === "number" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | null +>foo : string | number | undefined +>"number" : "number" + + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + if (typeof o?.["foo"] === "number") { +>typeof o?.["foo"] === "number" : boolean +>typeof o?.["foo"] : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.["foo"] : string | number | undefined +>o : Thing | null +>"foo" : "foo" +>"number" : "number" + + o["foo"]; +>o["foo"] : number +>o : Thing +>"foo" : "foo" + } + if (typeof o?.bar() === "number") { +>typeof o?.bar() === "number" : boolean +>typeof o?.bar() : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.bar() : number | undefined +>o?.bar : (() => number) | undefined +>o : Thing | null +>bar : (() => number) | undefined +>"number" : "number" + + o.bar; +>o.bar : () => number +>o : Thing +>bar : () => number + } + if (o?.baz instanceof Error) { +>o?.baz instanceof Error : boolean +>o?.baz : object | undefined +>o : Thing | null +>baz : object | undefined +>Error : ErrorConstructor + + o.baz; +>o.baz : Error +>o : Thing +>baz : Error + } +} + +function f22(o: Thing | undefined) { +>f22 : (o: Thing | undefined) => void +>o : Thing | undefined + + if (typeof o?.foo === "number") { +>typeof o?.foo === "number" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"number" : "number" + + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + else { + o.foo; // Error +>o.foo : string +>o : Thing | undefined +>foo : string + } + if (typeof o?.foo !== "number") { +>typeof o?.foo !== "number" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"number" : "number" + + o.foo; // Error +>o.foo : string +>o : Thing | undefined +>foo : string + } + else { + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + if (typeof o?.foo == "number") { +>typeof o?.foo == "number" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"number" : "number" + + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + else { + o.foo; // Error +>o.foo : string +>o : Thing | undefined +>foo : string + } + if (typeof o?.foo != "number") { +>typeof o?.foo != "number" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"number" : "number" + + o.foo; // Error +>o.foo : string +>o : Thing | undefined +>foo : string + } + else { + o.foo; +>o.foo : number +>o : Thing +>foo : number + } +} + +function f23(o: Thing | undefined) { +>f23 : (o: Thing | undefined) => void +>o : Thing | undefined + + if (typeof o?.foo === "undefined") { +>typeof o?.foo === "undefined" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"undefined" : "undefined" + + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + } + else { + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (typeof o?.foo !== "undefined") { +>typeof o?.foo !== "undefined" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"undefined" : "undefined" + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + else { + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + } + if (typeof o?.foo == "undefined") { +>typeof o?.foo == "undefined" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"undefined" : "undefined" + + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + } + else { + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (typeof o?.foo != "undefined") { +>typeof o?.foo != "undefined" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"undefined" : "undefined" + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + else { + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + } +} + +declare function assert(x: unknown): asserts x; +>assert : (x: unknown) => asserts x +>x : unknown + +declare function assertNonNull(x: T): asserts x is NonNullable; +>assertNonNull : (x: T) => asserts x is NonNullable +>x : T + +function f30(o: Thing | undefined) { +>f30 : (o: Thing | undefined) => void +>o : Thing | undefined + + if (!!true) { +>!!true : true +>!true : false +>true : true + + assert(o?.foo); +>assert(o?.foo) : void +>assert : (x: unknown) => asserts x +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } + if (!!true) { +>!!true : true +>!true : false +>true : true + + assert(o?.foo === 42); +>assert(o?.foo === 42) : void +>assert : (x: unknown) => asserts x +>o?.foo === 42 : boolean +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>42 : 42 + + o.foo; +>o.foo : 42 +>o : Thing +>foo : 42 + } + if (!!true) { +>!!true : true +>!true : false +>true : true + + assert(typeof o?.foo === "number"); +>assert(typeof o?.foo === "number") : void +>assert : (x: unknown) => asserts x +>typeof o?.foo === "number" : boolean +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined +>"number" : "number" + + o.foo; +>o.foo : number +>o : Thing +>foo : number + } + if (!!true) { +>!!true : true +>!true : false +>true : true + + assertNonNull(o?.foo); +>assertNonNull(o?.foo) : void +>assertNonNull : (x: T) => asserts x is NonNullable +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined + + o.foo; +>o.foo : string | number +>o : Thing +>foo : string | number + } +} + +function f40(o: Thing | undefined) { +>f40 : (o: Thing | undefined) => void +>o : Thing | undefined + + switch (o?.foo) { +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined + + case "abc": +>"abc" : "abc" + + o.foo; +>o.foo : "abc" +>o : Thing +>foo : "abc" + + break; + case 42: +>42 : 42 + + o.foo; +>o.foo : 42 +>o : Thing +>foo : 42 + + break; + case undefined: +>undefined : undefined + + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + + break; + default: + o.foo; // Error +>o.foo : string | number +>o : Thing | undefined +>foo : string | number + + break; + } +} + +function f41(o: Thing | undefined) { +>f41 : (o: Thing | undefined) => void +>o : Thing | undefined + + switch (typeof o?.foo) { +>typeof o?.foo : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>o?.foo : string | number | undefined +>o : Thing | undefined +>foo : string | number | undefined + + case "string": +>"string" : "string" + + o.foo; +>o.foo : string +>o : Thing +>foo : string + + break; + case "number": +>"number" : "number" + + o.foo; +>o.foo : number +>o : Thing +>foo : number + + break; + case "undefined": +>"undefined" : "undefined" + + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + + break; + default: + o.foo; // Error +>o.foo : never +>o : Thing | undefined +>foo : never + + break; + } +} + +// Repros from #34570 + +type Shape = +>Shape : Shape + + | { type: 'rectangle', width: number, height: number } +>type : "rectangle" +>width : number +>height : number + + | { type: 'circle', radius: number } +>type : "circle" +>radius : number + +function getArea(shape?: Shape) { +>getArea : (shape?: { type: "rectangle"; width: number; height: number; } | { type: "circle"; radius: number; } | undefined) => number +>shape : { type: "rectangle"; width: number; height: number; } | { type: "circle"; radius: number; } | undefined + + switch (shape?.type) { +>shape?.type : "rectangle" | "circle" | undefined +>shape : { type: "rectangle"; width: number; height: number; } | { type: "circle"; radius: number; } | undefined +>type : "rectangle" | "circle" | undefined + + case 'circle': +>'circle' : "circle" + + return Math.PI * shape.radius ** 2 +>Math.PI * shape.radius ** 2 : number +>Math.PI : number +>Math : Math +>PI : number +>shape.radius ** 2 : number +>shape.radius : number +>shape : { type: "circle"; radius: number; } +>radius : number +>2 : 2 + + case 'rectangle': +>'rectangle' : "rectangle" + + return shape.width * shape.height +>shape.width * shape.height : number +>shape.width : number +>shape : { type: "rectangle"; width: number; height: number; } +>width : number +>shape.height : number +>shape : { type: "rectangle"; width: number; height: number; } +>height : number + + default: + return 0 +>0 : 0 + } +} + +type Feature = { +>Feature : Feature + + id: string; +>id : string + + geometry?: { +>geometry : { type: string; coordinates: number[]; } | undefined + + type: string; +>type : string + + coordinates: number[]; +>coordinates : number[] + + }; +}; + + +function extractCoordinates(f: Feature): number[] { +>extractCoordinates : (f: Feature) => number[] +>f : Feature + + if (f.geometry?.type !== 'test') { +>f.geometry?.type !== 'test' : boolean +>f.geometry?.type : string | undefined +>f.geometry : { type: string; coordinates: number[]; } | undefined +>f : Feature +>geometry : { type: string; coordinates: number[]; } | undefined +>type : string | undefined +>'test' : "test" + + return []; +>[] : never[] + } + return f.geometry.coordinates; +>f.geometry.coordinates : number[] +>f.geometry : { type: string; coordinates: number[]; } +>f : Feature +>geometry : { type: string; coordinates: number[]; } +>coordinates : number[] +} + diff --git a/tests/baselines/reference/declarationEmitIndexTypeNotFound.errors.txt b/tests/baselines/reference/declarationEmitIndexTypeNotFound.errors.txt index 435ddd7c069..2e116a25861 100644 --- a/tests/baselines/reference/declarationEmitIndexTypeNotFound.errors.txt +++ b/tests/baselines/reference/declarationEmitIndexTypeNotFound.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/declarationEmitIndexTypeNotFound.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/declarationEmitIndexTypeNotFound.ts(2,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. tests/cases/compiler/declarationEmitIndexTypeNotFound.ts(2,13): error TS2304: Cannot find name 'TypeNotFound'. tests/cases/compiler/declarationEmitIndexTypeNotFound.ts(2,13): error TS4092: Parameter 'index' of index signature from exported interface has or is using private name 'TypeNotFound'. @@ -7,7 +7,7 @@ tests/cases/compiler/declarationEmitIndexTypeNotFound.ts(2,13): error TS4092: Pa export interface Test { [index: TypeNotFound]: any; ~~~~~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. ~~~~~~~~~~~~ !!! error TS2304: Cannot find name 'TypeNotFound'. ~~~~~~~~~~~~ diff --git a/tests/baselines/reference/decoratorMetadataWithImportDeclarationNameCollision4.errors.txt b/tests/baselines/reference/decoratorMetadataWithImportDeclarationNameCollision4.errors.txt index 611a0804812..e9d23681402 100644 --- a/tests/baselines/reference/decoratorMetadataWithImportDeclarationNameCollision4.errors.txt +++ b/tests/baselines/reference/decoratorMetadataWithImportDeclarationNameCollision4.errors.txt @@ -1,4 +1,4 @@ -tests/cases/compiler/service.ts(1,8): error TS1192: Module '"tests/cases/compiler/db"' has no default export. +tests/cases/compiler/service.ts(1,8): error TS2613: Module '"tests/cases/compiler/db"' has no default export. Did you mean to use 'import { db } from "tests/cases/compiler/db"' instead? ==== tests/cases/compiler/db.ts (0 errors) ==== @@ -10,7 +10,7 @@ tests/cases/compiler/service.ts(1,8): error TS1192: Module '"tests/cases/compile ==== tests/cases/compiler/service.ts (1 errors) ==== import db from './db'; // error no default export ~~ -!!! error TS1192: Module '"tests/cases/compiler/db"' has no default export. +!!! error TS2613: Module '"tests/cases/compiler/db"' has no default export. Did you mean to use 'import { db } from "tests/cases/compiler/db"' instead? function someDecorator(target) { return target; } diff --git a/tests/baselines/reference/decoratorOnClassMethodThisParameter.errors.txt b/tests/baselines/reference/decoratorOnClassMethodThisParameter.errors.txt index f87a3fa7f39..75afc6a07b7 100644 --- a/tests/baselines/reference/decoratorOnClassMethodThisParameter.errors.txt +++ b/tests/baselines/reference/decoratorOnClassMethodThisParameter.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethodThisParameter.ts(4,17): error TS1003: Identifier expected. +tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethodThisParameter.ts(4,17): error TS1359: Identifier expected. 'this' is a reserved word that cannot be used here. tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethodThisParameter.ts(4,17): error TS2680: A 'this' parameter must be the first parameter. @@ -8,7 +8,7 @@ tests/cases/conformance/decorators/class/method/parameter/decoratorOnClassMethod class C { method(@dec this: C) {} ~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'this' is a reserved word that cannot be used here. ~~~~~~~ !!! error TS2680: A 'this' parameter must be the first parameter. } \ No newline at end of file diff --git a/tests/baselines/reference/destructuringParameterDeclaration6.errors.txt b/tests/baselines/reference/destructuringParameterDeclaration6.errors.txt index cecb5d473c2..6fc9193fdb6 100644 --- a/tests/baselines/reference/destructuringParameterDeclaration6.errors.txt +++ b/tests/baselines/reference/destructuringParameterDeclaration6.errors.txt @@ -8,7 +8,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration6.ts( tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration6.ts(9,26): error TS2304: Cannot find name 'public'. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration6.ts(9,32): error TS1005: ';' expected. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration6.ts(9,33): error TS1128: Declaration or statement expected. -tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration6.ts(10,16): error TS1003: Identifier expected. +tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration6.ts(10,16): error TS1359: Identifier expected. 'while' is a reserved word that cannot be used here. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration6.ts(10,21): error TS1005: '(' expected. tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration6.ts(12,13): error TS2370: A rest parameter must be of an array type. @@ -45,7 +45,7 @@ tests/cases/conformance/es6/destructuring/destructuringParameterDeclaration6.ts( !!! error TS1128: Declaration or statement expected. function a5(...while) { } ~~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'while' is a reserved word that cannot be used here. ~ !!! error TS1005: '(' expected. function a6(...public) { } diff --git a/tests/baselines/reference/docker/azure-sdk.log b/tests/baselines/reference/docker/azure-sdk.log index e655cbad646..03b78facc92 100644 --- a/tests/baselines/reference/docker/azure-sdk.log +++ b/tests/baselines/reference/docker/azure-sdk.log @@ -2,58 +2,30 @@ Exit Code: 1 Standard output: Rush Multi-Project Build Tool 5.X.X - https://rushjs.io -Node.js version is 12.10.0 (pre-LTS) +Node.js version is 12.12.0 (pre-LTS) Starting "rush rebuild" Executing a maximum of ?simultaneous processes... -XX of XX: [@azure/abort-controller] completed successfully in ? seconds -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. XX of XX: [@azure/core-tracing] completed successfully in ? seconds -XX of XX: [@azure/core-http] completed successfully in ? seconds -XX of XX: [@azure/identity] completed successfully in ? seconds -XX of XX: [@azure/core-amqp] completed successfully in ? seconds -XX of XX: [@azure/core-arm] completed successfully in ? seconds -XX of XX: [@azure/core-paging] completed successfully in ? seconds -XX of XX: [@azure/test-utils-recorder] completed successfully in ? seconds -Warning: You have changed the public API signature for this project. Updating review/event-hubs.api.md -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/core-amqp/typings/src/requestResponseLink.d.ts:41:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventDataBatch.d.ts:60:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventDataBatch.d.ts:66:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventDataBatch.d.ts:71:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventDataBatch.d.ts:82:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventHubClient.d.ts:235:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventHubClient.d.ts:242:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventHubReceiver.d.ts:131:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventHubReceiver.d.ts:136:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventProcessor.d.ts:206:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/linkEntity.d.ts:126:17 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/linkEntity.d.ts:126:17 - (TS7033) Property '_type' implicitly has type 'any', because its get accessor lacks a return type annotation. -Warning: typings/src/partitionProcessor.d.ts:74:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:80:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:85:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:89:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:94:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:98:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:103:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:107:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:112:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:116:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:120:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:124:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiveHandler.d.ts:24:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiveHandler.d.ts:29:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiveHandler.d.ts:35:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:79:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:85:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:91:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:97:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:107:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:112:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/sender.d.ts:38:9 - (TS1086) An accessor cannot be declared in an ambient context. +npm ERR! code ELIFECYCLE +npm ERR! errno 2 +npm ERR! @azure/core-http@X.X.X-preview.5 build:tsc: `tsc -p tsconfig.es.json` +npm ERR! Exit status 2 +npm ERR! +npm ERR! Failed at the @azure/core-http@X.X.X-preview.5 build:tsc script. +npm ERR! This is probably not a problem with npm. There is likely additional logging output above. +npm ERR! A complete log of this run can be found in: +npm ERR! /root/.npm/_logs/XXXX-XX-XXXXXXXXX-debug.log +ERROR: "build:tsc" exited with 2. +npm ERR! code ELIFECYCLE +npm ERR! errno 1 +npm ERR! @azure/core-http@X.X.X-preview.5 build:lib: `run-s build:tsc build:rollup build:minify-browser` +npm ERR! Exit status 1 +npm ERR! +npm ERR! Failed at the @azure/core-http@X.X.X-preview.5 build:lib script. +npm ERR! This is probably not a problem with npm. There is likely additional logging output above. +npm ERR! A complete log of this run can be found in: +npm ERR! /root/.npm/_logs/XXXX-XX-XXXXXXXXX-debug.log +ERROR: "build:lib" exited with 1. Warning: You have changed the public API signature for this project. Updating review/event-processor-host.api.md Warning: typings/src/eventProcessorHost.d.ts:32:9 - (TS1086) An accessor cannot be declared in an ambient context. Warning: typings/src/eventProcessorHost.d.ts:36:9 - (TS1086) An accessor cannot be declared in an ambient context. @@ -63,17 +35,11 @@ Warning: typings/src/partitionContext.d.ts:27:9 - (TS1086) An accessor cannot be Warning: typings/src/partitionContext.d.ts:32:9 - (TS1086) An accessor cannot be declared in an ambient context. Warning: typings/src/partitionPump.d.ts:17:9 - (TS1086) An accessor cannot be declared in an ambient context. Warning: typings/src/partitionPump.d.ts:18:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: You have changed the public API signature for this project. Updating review/app-configuration.api.md -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. +XX of XX: [@azure/test-utils-recorder] completed successfully in ? seconds +XX of XX: [@azure/abort-controller] completed successfully in ? seconds XX of XX: [@azure/core-asynciterator-polyfill] completed successfully in ? seconds +XX of XX: [@azure/core-auth] completed successfully in ? seconds +XX of XX: [@azure/core-paging] completed successfully in ? seconds Warning: You have changed the public API signature for this project. Updating review/cosmos.api.md Warning: dist-esm/ChangeFeedIterator.d.ts:27:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. Warning: dist-esm/ChangeFeedResponse.d.ts:21:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. @@ -90,9 +56,9 @@ Warning: dist-esm/client/Database/Database.d.ts:41:9 - (TS1056) Accessors are on Warning: dist-esm/client/Item/Item.d.ts:20:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. Warning: dist-esm/client/Offer/Offer.d.ts:18:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. Warning: dist-esm/client/Permission/Permission.d.ts:18:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. -Warning: dist-esm/client/Script/Scripts.d.ts:39:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. -Warning: dist-esm/client/Script/Scripts.d.ts:46:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. -Warning: dist-esm/client/Script/Scripts.d.ts:53:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Script/Scripts.d.ts:41:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Script/Scripts.d.ts:48:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Script/Scripts.d.ts:55:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. Warning: dist-esm/client/StoredProcedure/StoredProcedure.d.ts:18:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. Warning: dist-esm/client/StoredProcedure/StoredProcedureResponse.d.ts:17:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. Warning: dist-esm/client/Trigger/Trigger.d.ts:18:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. @@ -111,76 +77,8 @@ Warning: dist-esm/request/ResourceResponse.d.ts:9:9 - (TS1056) Accessors are onl Warning: dist-esm/request/ResourceResponse.d.ts:10:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. Warning: dist-esm/request/ResourceResponse.d.ts:11:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. dist-esm/index.js → dist/index.js... -(!) Unresolved dependencies -https://rollupjs.org/guide/en/#warning-treating-module-as-external-dependency -tslib (imported by dist-esm/auth.js, dist-esm/queryIterator.js, dist-esm/CosmosClient.js, dist-esm/plugins/Plugin.js, dist-esm/ClientContext.js, dist-esm/globalEndpointManager.js, dist-esm/client/Conflict/Conflict.js, dist-esm/client/Container/Container.js, dist-esm/client/Database/Database.js, dist-esm/client/Container/Containers.js, dist-esm/client/Database/Databases.js, dist-esm/client/Item/Item.js, dist-esm/client/Item/Items.js, dist-esm/client/Offer/Offer.js, dist-esm/client/Permission/Permission.js, dist-esm/client/Permission/Permissions.js, dist-esm/client/StoredProcedure/StoredProcedure.js, dist-esm/client/StoredProcedure/StoredProcedures.js, dist-esm/client/Trigger/Trigger.js, dist-esm/client/Trigger/Triggers.js, dist-esm/client/User/User.js, dist-esm/client/User/Users.js, dist-esm/client/UserDefinedFunction/UserDefinedFunction.js, dist-esm/client/UserDefinedFunction/UserDefinedFunctions.js, dist-esm/queryExecutionContext/defaultQueryExecutionContext.js, dist-esm/queryExecutionContext/documentProducer.js, dist-esm/queryExecutionContext/parallelQueryExecutionContextBase.js, dist-esm/queryExecutionContext/pipelinedQueryExecutionContext.js, dist-esm/request/request.js, dist-esm/request/RequestHandler.js, dist-esm/ChangeFeedIterator.js, dist-esm/routing/smartRoutingMapProvider.js, dist-esm/queryExecutionContext/EndpointComponent/AggregateEndpointComponent.js, dist-esm/queryExecutionContext/EndpointComponent/OrderByEndpointComponent.js, dist-esm/queryExecutionContext/EndpointComponent/OffsetLimitEndpointComponent.js, dist-esm/queryExecutionContext/EndpointComponent/OrderedDistinctEndpointComponent.js, dist-esm/queryExecutionContext/EndpointComponent/UnorderedDistinctEndpointComponent.js, dist-esm/retry/retryUtility.js, dist-esm/routing/partitionKeyRangeCache.js, dist-esm/retry/defaultRetryPolicy.js, dist-esm/retry/endpointDiscoveryRetryPolicy.js, dist-esm/retry/resourceThrottleRetryPolicy.js, dist-esm/retry/sessionRetryPolicy.js) -@azure/cosmos-sign (imported by dist-esm/auth.js) -universal-user-agent (imported by dist-esm/common/platform.js) -uuid/v4 (imported by dist-esm/ClientContext.js, dist-esm/client/Item/Items.js) -binary-search-bounds (imported by dist-esm/queryExecutionContext/parallelQueryExecutionContextBase.js, dist-esm/routing/inMemoryCollectionRoutingMap.js) -priorityqueuejs (imported by dist-esm/queryExecutionContext/parallelQueryExecutionContextBase.js) -semaphore (imported by dist-esm/queryExecutionContext/parallelQueryExecutionContextBase.js) -debug (imported by dist-esm/common/logger.js) -node-abort-controller (imported by dist-esm/request/RequestHandler.js) -node-fetch (imported by dist-esm/request/RequestHandler.js) -atob (imported by dist-esm/session/sessionContainer.js) -crypto-hash (imported by dist-esm/queryExecutionContext/EndpointComponent/OrderedDistinctEndpointComponent.js, dist-esm/queryExecutionContext/EndpointComponent/UnorderedDistinctEndpointComponent.js) -fast-json-stable-stringify (imported by dist-esm/queryExecutionContext/EndpointComponent/OrderedDistinctEndpointComponent.js, dist-esm/queryExecutionContext/EndpointComponent/UnorderedDistinctEndpointComponent.js) -(!) Missing global variable names -Use output.globals to specify browser global variable names corresponding to external modules -universal-user-agent (guessing 'universalUserAgent') -tslib (guessing 'tslib') -@azure/cosmos-sign (guessing 'cosmosSign') -debug (guessing 'debugLib') -binary-search-bounds (guessing 'bs') -priorityqueuejs (guessing 'PriorityQueue') -semaphore (guessing 'semaphore') -crypto-hash (guessing 'cryptoHash') -fast-json-stable-stringify (guessing 'stableStringify') -uuid/v4 (guessing 'uuid') -node-abort-controller (guessing 'AbortController') -node-fetch (guessing 'fetch') -atob (guessing 'atob') -(!) Circular dependency: dist-esm/queryExecutionContext/index.js -> dist-esm/queryExecutionContext/headerUtils.js -> dist-esm/queryMetrics/index.js -> dist-esm/queryMetrics/clientSideMetrics.js -> dist-esm/queryExecutionContext/index.js -(!) Circular dependency: dist-esm/index.js -> dist-esm/CosmosClient.js -> dist-esm/client/Database/index.js -> dist-esm/client/Database/Database.js -> dist-esm/client/Container/index.js -> dist-esm/client/Container/Container.js -> dist-esm/client/Script/Scripts.js -> dist-esm/index.js -(!) Circular dependency: dist-esm/request/RequestHandler.js -> dist-esm/retry/retryUtility.js -> dist-esm/request/RequestHandler.js created dist/index.js in ?s -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/core-amqp/typings/src/requestResponseLink.d.ts:41:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:192:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:198:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:203:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:214:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:254:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:261:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:541:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:547:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:553:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:559:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:569:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:574:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:715:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:982:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1287:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1293:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1298:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1302:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1307:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1311:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1316:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1320:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1325:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1329:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1333:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1337:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1477:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1482:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1488:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. +XX of XX: [@azure/logger] completed successfully in ? seconds Warning: You have changed the public API signature for this project. Updating review/service-bus.api.md Warning: typings/src/receiver.d.ts:28:9 - (TS1086) An accessor cannot be declared in an ambient context. Warning: typings/src/receiver.d.ts:34:9 - (TS1086) An accessor cannot be declared in an ambient context. @@ -193,71 +91,23 @@ Warning: typings/src/serviceBusMessage.d.ts:453:9 - (TS1086) An accessor cannot XX of XX: [@azure/storage-blob] completed successfully in ? seconds XX of XX: [@azure/storage-file] completed successfully in ? seconds XX of XX: [@azure/storage-queue] completed successfully in ? seconds -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. XX of XX: [testhub] completed successfully in ? seconds -SUCCESS (13) +SUCCESS (11) ================================ -@azure/abort-controller (? seconds) @azure/core-tracing (? seconds) -@azure/core-http (? seconds) -@azure/identity (? seconds) -@azure/core-amqp (? seconds) -@azure/core-arm (? seconds) -@azure/core-paging (? seconds) @azure/test-utils-recorder (? seconds) +@azure/abort-controller (? seconds) @azure/core-asynciterator-polyfill (? seconds) +@azure/core-auth (? seconds) +@azure/core-paging (? seconds) +@azure/logger (? seconds) @azure/storage-blob (? seconds) @azure/storage-file (? seconds) @azure/storage-queue (? seconds) testhub (? seconds) ================================ -SUCCESS WITH WARNINGS (11) +SUCCESS WITH WARNINGS (3) ================================ -@azure/core-auth (? seconds) -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. -@azure/event-hubs (? seconds) -Warning: You have changed the public API signature for this project. Updating review/event-hubs.api.md -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/core-amqp/typings/src/requestResponseLink.d.ts:41:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventDataBatch.d.ts:60:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventDataBatch.d.ts:66:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventDataBatch.d.ts:71:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventDataBatch.d.ts:82:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventHubClient.d.ts:235:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventHubClient.d.ts:242:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventHubReceiver.d.ts:131:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventHubReceiver.d.ts:136:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/eventProcessor.d.ts:206:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/linkEntity.d.ts:126:17 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/linkEntity.d.ts:126:17 - (TS7033) Property '_type' implicitly has type 'any', because its get accessor lacks a return type annotation. -Warning: typings/src/partitionProcessor.d.ts:74:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:80:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:85:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:89:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:94:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:98:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:103:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:107:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:112:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:116:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:120:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/partitionProcessor.d.ts:124:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiveHandler.d.ts:24:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiveHandler.d.ts:29:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiveHandler.d.ts:35:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:79:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:85:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:91:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:97:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:107:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/receiver.d.ts:112:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: typings/src/sender.d.ts:38:9 - (TS1086) An accessor cannot be declared in an ambient context. @azure/event-processor-host (? seconds) Warning: You have changed the public API signature for this project. Updating review/event-processor-host.api.md Warning: typings/src/eventProcessorHost.d.ts:32:9 - (TS1086) An accessor cannot be declared in an ambient context. @@ -268,19 +118,6 @@ Warning: typings/src/partitionContext.d.ts:27:9 - (TS1086) An accessor cannot be Warning: typings/src/partitionContext.d.ts:32:9 - (TS1086) An accessor cannot be declared in an ambient context. Warning: typings/src/partitionPump.d.ts:17:9 - (TS1086) An accessor cannot be declared in an ambient context. Warning: typings/src/partitionPump.d.ts:18:9 - (TS1086) An accessor cannot be declared in an ambient context. -@azure/keyvault-keys (? seconds) -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. -@azure/keyvault-secrets (? seconds) -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. -@azure/app-configuration (? seconds) -Warning: You have changed the public API signature for this project. Updating review/app-configuration.api.md -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. @azure/cosmos (? seconds) Warning: You have changed the public API signature for this project. Updating review/cosmos.api.md Warning: dist-esm/ChangeFeedIterator.d.ts:27:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. @@ -292,65 +129,34 @@ Warning: dist-esm/ChangeFeedResponse.d.ts:45:9 - (TS1056) Accessors are only ava Warning: dist-esm/client/Conflict/Conflict.d.ts:17:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. Warning: dist-esm/client/Container/Container.d.ts:39:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. Warning: dist-esm/client/Container/Container.d.ts:44:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. -[...41 lines omitted...] -fast-json-stable-stringify (imported by dist-esm/queryExecutionContext/EndpointComponent/OrderedDistinctEndpointComponent.js, dist-esm/queryExecutionContext/EndpointComponent/UnorderedDistinctEndpointComponent.js) -(!) Missing global variable names -Use output.globals to specify browser global variable names corresponding to external modules -universal-user-agent (guessing 'universalUserAgent') -tslib (guessing 'tslib') -@azure/cosmos-sign (guessing 'cosmosSign') -debug (guessing 'debugLib') -binary-search-bounds (guessing 'bs') -priorityqueuejs (guessing 'PriorityQueue') -semaphore (guessing 'semaphore') -crypto-hash (guessing 'cryptoHash') -fast-json-stable-stringify (guessing 'stableStringify') -uuid/v4 (guessing 'uuid') -node-abort-controller (guessing 'AbortController') -node-fetch (guessing 'fetch') -atob (guessing 'atob') -(!) Circular dependency: dist-esm/queryExecutionContext/index.js -> dist-esm/queryExecutionContext/headerUtils.js -> dist-esm/queryMetrics/index.js -> dist-esm/queryMetrics/clientSideMetrics.js -> dist-esm/queryExecutionContext/index.js -(!) Circular dependency: dist-esm/index.js -> dist-esm/CosmosClient.js -> dist-esm/client/Database/index.js -> dist-esm/client/Database/Database.js -> dist-esm/client/Container/index.js -> dist-esm/client/Container/Container.js -> dist-esm/client/Script/Scripts.js -> dist-esm/index.js -(!) Circular dependency: dist-esm/request/RequestHandler.js -> dist-esm/retry/retryUtility.js -> dist-esm/request/RequestHandler.js +Warning: dist-esm/client/Container/Container.d.ts:51:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Container/Container.d.ts:55:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Database/Database.d.ts:41:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Item/Item.d.ts:20:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Offer/Offer.d.ts:18:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Permission/Permission.d.ts:18:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Script/Scripts.d.ts:41:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Script/Scripts.d.ts:48:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Script/Scripts.d.ts:55:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/StoredProcedure/StoredProcedure.d.ts:18:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/StoredProcedure/StoredProcedureResponse.d.ts:17:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/Trigger/Trigger.d.ts:18:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/User/User.d.ts:27:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/UserDefinedFunction/UserDefinedFunction.d.ts:18:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/client/UserDefinedFunction/UserDefinedFunctionResponse.d.ts:15:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/queryMetrics/queryMetrics.d.ts:26:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/FeedResponse.d.ts:7:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/FeedResponse.d.ts:8:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/FeedResponse.d.ts:9:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/FeedResponse.d.ts:10:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/LocationRouting.d.ts:8:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/LocationRouting.d.ts:9:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/LocationRouting.d.ts:10:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/ResourceResponse.d.ts:9:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/ResourceResponse.d.ts:10:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +Warning: dist-esm/request/ResourceResponse.d.ts:11:9 - (TS1056) Accessors are only available when targeting ECMAScript 5 and higher. +dist-esm/index.js → dist/index.js... created dist/index.js in ?s -@azure/eventhubs-checkpointstore-blob (? seconds) -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/core-amqp/typings/src/requestResponseLink.d.ts:41:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:192:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:198:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:203:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:214:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:254:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:261:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:541:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:547:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:553:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:559:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:569:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:574:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:715:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:982:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1287:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1293:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1298:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1302:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1307:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1311:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1316:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1320:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1325:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1329:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1333:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1337:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1477:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1482:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/eventhub/event-hubs/typings/event-hubs.d.ts:1488:9 - (TS1086) An accessor cannot be declared in an ambient context. -@azure/keyvault-certificates ( ? seconds) -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. @azure/service-bus (? seconds) Warning: You have changed the public API signature for this project. Updating review/service-bus.api.md Warning: typings/src/receiver.d.ts:28:9 - (TS1086) An accessor cannot be declared in an ambient context. @@ -361,25 +167,65 @@ Warning: typings/src/receiver.d.ts:165:9 - (TS1086) An accessor cannot be declar Warning: typings/src/receiver.d.ts:175:9 - (TS1086) An accessor cannot be declared in an ambient context. Warning: typings/src/sender.d.ts:24:9 - (TS1086) An accessor cannot be declared in an ambient context. Warning: typings/src/serviceBusMessage.d.ts:453:9 - (TS1086) An accessor cannot be declared in an ambient context. -@azure/template (? seconds) -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortController.d.ts:73:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:44:9 - (TS1086) An accessor cannot be declared in an ambient context. -Warning: /azure-sdk/sdk/core/abort-controller/types/src/AbortSignal.d.ts:53:16 - (TS1086) An accessor cannot be declared in an ambient context. ================================ -rush rebuild ( ? seconds) +BLOCKED (11) +================================ +@azure/identity +@azure/core-amqp +@azure/core-arm +@azure/event-hubs +@azure/app-configuration +@azure/core-lro +@azure/eventhubs-checkpointstore-blob +@azure/keyvault-certificates +@azure/keyvault-keys +@azure/keyvault-secrets +@azure/template +================================ +FAILURE (1) +================================ +@azure/core-http ( ? seconds) +npm ERR! code ELIFECYCLE +npm ERR! errno 2 +npm ERR! @azure/core-http@X.X.X-preview.5 build:tsc: `tsc -p tsconfig.es.json` +npm ERR! Exit status 2 +npm ERR! +npm ERR! Failed at the @azure/core-http@X.X.X-preview.5 build:tsc script. +npm ERR! This is probably not a problem with npm. There is likely additional logging output above. +npm ERR! A complete log of this run can be found in: +npm ERR! /root/.npm/_logs/XXXX-XX-XXXXXXXXX-debug.log +ERROR: "build:tsc" exited with 2. +npm ERR! code ELIFECYCLE +npm ERR! errno 1 +npm ERR! @azure/core-http@X.X.X-preview.5 build:lib: `run-s build:tsc build:rollup build:minify-browser` +npm ERR! Exit status 1 +npm ERR! +npm ERR! Failed at the @azure/core-http@X.X.X-preview.5 build:lib script. +npm ERR! This is probably not a problem with npm. There is likely additional logging output above. +npm ERR! A complete log of this run can be found in: +npm ERR! /root/.npm/_logs/XXXX-XX-XXXXXXXXX-debug.log +ERROR: "build:lib" exited with 1. +================================ +Error: Project(s) failed to build +rush rebuild - Errors! ( ? seconds) Standard error: -XX of XX: [@azure/core-auth] completed with warnings in ? seconds -XX of XX: [@azure/event-hubs] completed with warnings in ? seconds + +XX of XX: [@azure/core-http] failed to build! +XX of XX: [@azure/app-configuration] blocked by [@azure/core-http]! +XX of XX: [@azure/core-arm] blocked by [@azure/core-http]! +XX of XX: [@azure/core-lro] blocked by [@azure/core-http]! +XX of XX: [@azure/keyvault-certificates] blocked by [@azure/core-http]! +XX of XX: [@azure/identity] blocked by [@azure/core-http]! +XX of XX: [@azure/core-amqp] blocked by [@azure/core-http]! +XX of XX: [@azure/event-hubs] blocked by [@azure/core-http]! +XX of XX: [@azure/eventhubs-checkpointstore-blob] blocked by [@azure/core-http]! +XX of XX: [@azure/keyvault-keys] blocked by [@azure/core-http]! +XX of XX: [@azure/keyvault-secrets] blocked by [@azure/core-http]! +XX of XX: [@azure/template] blocked by [@azure/core-http]! XX of XX: [@azure/event-processor-host] completed with warnings in ? seconds -XX of XX: [@azure/keyvault-keys] completed with warnings in ? seconds -XX of XX: [@azure/keyvault-secrets] completed with warnings in ? seconds -XX of XX: [@azure/app-configuration] completed with warnings in ? seconds XX of XX: [@azure/cosmos] completed with warnings in ? seconds -XX of XX: [@azure/eventhubs-checkpointstore-blob] completed with warnings in ? seconds -XX of XX: [@azure/keyvault-certificates] completed with warnings in ? seconds XX of XX: [@azure/service-bus] completed with warnings in ? seconds -XX of XX: [@azure/template] completed with warnings in ? seconds -Project(s) succeeded with warnings +[@azure/core-http] Returned error code: 1 diff --git a/tests/baselines/reference/docker/office-ui-fabric.log b/tests/baselines/reference/docker/office-ui-fabric.log index 9af785894ce..f9dd067367f 100644 --- a/tests/baselines/reference/docker/office-ui-fabric.log +++ b/tests/baselines/reference/docker/office-ui-fabric.log @@ -1,72 +1,66 @@ Exit Code: 1 Standard output: @uifabric/build: yarn run vX.X.X -@uifabric/build: $ node ./just-scripts.js no-op --production --lint +@uifabric/build: $ node ./just-scripts.js no-op @uifabric/build: Done in ?s. @uifabric/example-data: yarn run vX.X.X -@uifabric/example-data: $ just-scripts build --production --lint +@uifabric/example-data: $ just-scripts build @uifabric/example-data: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] @uifabric/example-data: [XX:XX:XX XM] ■ Running tslint @uifabric/example-data: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/example-data/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib @uifabric/example-data: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/example-data/tsconfig.json -@uifabric/example-data: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/example-data/tsconfig.json" +@uifabric/example-data: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/example-data/tsconfig.json" @uifabric/example-data: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/example-data/tsconfig.json -@uifabric/example-data: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module esnext --project "/office-ui-fabric-react/packages/example-data/tsconfig.json" -@uifabric/example-data: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/example-data/tsconfig.json -@uifabric/example-data: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/example-data/tsconfig.json" +@uifabric/example-data: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module esnext --project "/office-ui-fabric-react/packages/example-data/tsconfig.json" @uifabric/example-data: [XX:XX:XX XM] ■ Running Webpack @uifabric/example-data: [XX:XX:XX XM] ■ Webpack Config Path: /office-ui-fabric-react/packages/example-data/webpack.config.js @uifabric/example-data: Webpack version: 4.29.5 @uifabric/example-data: [XX:XX:XX XM] ■ Extracting Public API surface from '/office-ui-fabric-react/packages/example-data/lib/index.d.ts' @uifabric/example-data: Done in ?s. @uifabric/migration: yarn run vX.X.X -@uifabric/migration: $ just-scripts build --production --lint +@uifabric/migration: $ just-scripts build @uifabric/migration: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] @uifabric/migration: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/migration/tsconfig.json -@uifabric/migration: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module commonjs --project "/office-ui-fabric-react/packages/migration/tsconfig.json" +@uifabric/migration: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module commonjs --project "/office-ui-fabric-react/packages/migration/tsconfig.json" @uifabric/migration: Done in ?s. @uifabric/monaco-editor: yarn run vX.X.X -@uifabric/monaco-editor: $ just-scripts build --production --lint +@uifabric/monaco-editor: $ just-scripts build @uifabric/monaco-editor: [XX:XX:XX XM] ■ Removing [esm, lib, lib-commonjs] @uifabric/monaco-editor: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/monaco-editor/tsconfig.json -@uifabric/monaco-editor: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module esnext --project "/office-ui-fabric-react/packages/monaco-editor/tsconfig.json" +@uifabric/monaco-editor: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module esnext --project "/office-ui-fabric-react/packages/monaco-editor/tsconfig.json" @uifabric/monaco-editor: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/monaco-editor/tsconfig.json -@uifabric/monaco-editor: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/monaco-editor/tsconfig.json" +@uifabric/monaco-editor: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/monaco-editor/tsconfig.json" @uifabric/monaco-editor: Done in ?s. @uifabric/set-version: yarn run vX.X.X -@uifabric/set-version: $ just-scripts build --production --lint +@uifabric/set-version: $ just-scripts build @uifabric/set-version: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] @uifabric/set-version: [XX:XX:XX XM] ■ Running tslint @uifabric/set-version: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib @uifabric/set-version: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/set-version/tsconfig.json -@uifabric/set-version: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" +@uifabric/set-version: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" @uifabric/set-version: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/set-version/tsconfig.json -@uifabric/set-version: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module esnext --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" -@uifabric/set-version: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/set-version/tsconfig.json -@uifabric/set-version: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" +@uifabric/set-version: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module esnext --project "/office-ui-fabric-react/packages/set-version/tsconfig.json" @uifabric/set-version: [XX:XX:XX XM] ■ Running Webpack @uifabric/set-version: [XX:XX:XX XM] ■ Webpack Config Path: null @uifabric/set-version: [XX:XX:XX XM] ■ webpack.config.js not found, skipping webpack @uifabric/set-version: Done in ?s. @uifabric/webpack-utils: yarn run vX.X.X -@uifabric/webpack-utils: $ just-scripts build --production --lint +@uifabric/webpack-utils: $ just-scripts build @uifabric/webpack-utils: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] @uifabric/webpack-utils: [XX:XX:XX XM] ■ Running tslint @uifabric/webpack-utils: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/webpack-utils/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib @uifabric/webpack-utils: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/webpack-utils/tsconfig.json -@uifabric/webpack-utils: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module commonjs --project "/office-ui-fabric-react/packages/webpack-utils/tsconfig.json" +@uifabric/webpack-utils: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module commonjs --project "/office-ui-fabric-react/packages/webpack-utils/tsconfig.json" @uifabric/webpack-utils: Done in ?s. @uifabric/merge-styles: yarn run vX.X.X -@uifabric/merge-styles: $ just-scripts build --production --lint +@uifabric/merge-styles: $ just-scripts build @uifabric/merge-styles: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] @uifabric/merge-styles: [XX:XX:XX XM] ■ Running tslint @uifabric/merge-styles: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib @uifabric/merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/merge-styles/tsconfig.json -@uifabric/merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" +@uifabric/merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" @uifabric/merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/merge-styles/tsconfig.json -@uifabric/merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module esnext --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" -@uifabric/merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/merge-styles/tsconfig.json -@uifabric/merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" +@uifabric/merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module esnext --project "/office-ui-fabric-react/packages/merge-styles/tsconfig.json" @uifabric/merge-styles: [XX:XX:XX XM] ■ Running Jest @uifabric/merge-styles: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/jest/bin/jest.js" --config "/office-ui-fabric-react/packages/merge-styles/jest.config.js" --passWithNoTests --colors --forceExit @uifabric/merge-styles: [XX:XX:XX XM] ■ Running Webpack @@ -89,38 +83,32 @@ Standard output: @uifabric/merge-styles: [XX:XX:XX XM] ■ Extracting Public API surface from '/office-ui-fabric-react/packages/merge-styles/lib/index.d.ts' @uifabric/merge-styles: Done in ?s. @uifabric/jest-serializer-merge-styles: yarn run vX.X.X -@uifabric/jest-serializer-merge-styles: $ just-scripts build --production --lint +@uifabric/jest-serializer-merge-styles: $ just-scripts build @uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json -@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json" +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json" @uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json -@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module esnext --project "/office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json" -@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json -@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json" +@uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module esnext --project "/office-ui-fabric-react/packages/jest-serializer-merge-styles/tsconfig.json" @uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ Running Jest @uifabric/jest-serializer-merge-styles: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/jest/bin/jest.js" --config "/office-ui-fabric-react/packages/jest-serializer-merge-styles/jest.config.js" --passWithNoTests --colors --forceExit @uifabric/jest-serializer-merge-styles: PASS src/index.test.tsx @uifabric/jest-serializer-merge-styles: Done in ?s. @uifabric/test-utilities: yarn run vX.X.X -@uifabric/test-utilities: $ just-scripts build --production --lint +@uifabric/test-utilities: $ just-scripts build @uifabric/test-utilities: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] @uifabric/test-utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/test-utilities/tsconfig.json -@uifabric/test-utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/test-utilities/tsconfig.json" +@uifabric/test-utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/test-utilities/tsconfig.json" @uifabric/test-utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/test-utilities/tsconfig.json -@uifabric/test-utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module esnext --project "/office-ui-fabric-react/packages/test-utilities/tsconfig.json" -@uifabric/test-utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/test-utilities/tsconfig.json -@uifabric/test-utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/test-utilities/tsconfig.json" +@uifabric/test-utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module esnext --project "/office-ui-fabric-react/packages/test-utilities/tsconfig.json" @uifabric/test-utilities: Done in ?s. @uifabric/utilities: yarn run vX.X.X -@uifabric/utilities: $ just-scripts build --production --lint +@uifabric/utilities: $ just-scripts build @uifabric/utilities: [XX:XX:XX XM] ■ Removing [lib, temp, dist, lib-amd, lib-commonjs, lib-es2015, coverage, src/**/*.scss.ts] @uifabric/utilities: [XX:XX:XX XM] ■ Running tslint @uifabric/utilities: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/tslint/lib/tslintCli.js" --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" -t stylish -r /office-ui-fabric-react/node_modules/tslint-microsoft-contrib @uifabric/utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/utilities/tsconfig.json -@uifabric/utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" +@uifabric/utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib-commonjs --module commonjs --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" @uifabric/utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/utilities/tsconfig.json -@uifabric/utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib --module esnext --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" -@uifabric/utilities: [XX:XX:XX XM] ■ Running /office-ui-fabric-react/node_modules/typescript/lib/tsc.js with /office-ui-fabric-react/packages/utilities/tsconfig.json -@uifabric/utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --inlineSources --sourceRoot "../src" --outDir lib-amd --module amd --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" +@uifabric/utilities: [XX:XX:XX XM] ■ Executing: /usr/local/bin/node "/office-ui-fabric-react/node_modules/typescript/lib/tsc.js" --pretty --target es5 --outDir lib --module esnext --project "/office-ui-fabric-react/packages/utilities/tsconfig.json" @uifabric/utilities: [XX:XX:XX XM] ■ Running Jest @uifabric/utilities: [XX:XX:XX XM] ■ /usr/local/bin/node "/office-ui-fabric-react/node_modules/jest/bin/jest.js" --config "/office-ui-fabric-react/packages/utilities/jest.config.js" --passWithNoTests --colors --forceExit @uifabric/utilities: [XX:XX:XX XM] ■ Running Webpack @@ -168,7 +156,7 @@ Standard output: Standard error: info cli using local version of lerna lerna notice cli vX.X.X -lerna info Executing command in 42 packages: "yarn run build --production --lint" +lerna info Executing command in 42 packages: "yarn run build" @uifabric/example-data: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect @uifabric/set-version: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect @uifabric/merge-styles: [XX:XX:XX XM] ▲ One of these [node-sass, postcss, autoprefixer] is not installed, so this task has no effect @@ -192,4 +180,4 @@ lerna info Executing command in 42 packages: "yarn run build --production --lint @uifabric/utilities: [XX:XX:XX XM] x ------------------------------------ @uifabric/utilities: [XX:XX:XX XM] x Error previously detected. See above for error messages. @uifabric/utilities: error Command failed with exit code 1. -lerna ERR! yarn run build --production --lint exited 1 in '@uifabric/utilities' +lerna ERR! yarn run build exited 1 in '@uifabric/utilities' diff --git a/tests/baselines/reference/elementAccessChain.js b/tests/baselines/reference/elementAccessChain.js index bf7804ff2cf..e01480eb68b 100644 --- a/tests/baselines/reference/elementAccessChain.js +++ b/tests/baselines/reference/elementAccessChain.js @@ -19,11 +19,14 @@ o5.b?.()["c"].d?.e; o5.b?.()["c"].d?.["e"]; o5["b"]?.()["c"].d?.e; o5["b"]?.()["c"].d?.["e"]; - + +// GH#33744 +declare const o6: () => undefined | ({ x: number }); +o6()?.["x"]; //// [elementAccessChain.js] "use strict"; -var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w; +var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, _v, _w, _x; (_a = o1) === null || _a === void 0 ? void 0 : _a["b"]; (_b = o2) === null || _b === void 0 ? void 0 : _b["b"].c; (_c = o2) === null || _c === void 0 ? void 0 : _c.b["c"]; @@ -35,3 +38,4 @@ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r, _s, _t, _u, (_q = (_p = (_o = o5).b) === null || _p === void 0 ? void 0 : _p.call(_o)["c"].d) === null || _q === void 0 ? void 0 : _q["e"]; (_t = (_s = (_r = o5)["b"]) === null || _s === void 0 ? void 0 : _s.call(_r)["c"].d) === null || _t === void 0 ? void 0 : _t.e; (_w = (_v = (_u = o5)["b"]) === null || _v === void 0 ? void 0 : _v.call(_u)["c"].d) === null || _w === void 0 ? void 0 : _w["e"]; +(_x = o6()) === null || _x === void 0 ? void 0 : _x["x"]; diff --git a/tests/baselines/reference/elementAccessChain.symbols b/tests/baselines/reference/elementAccessChain.symbols index af253ccd4bf..5e892012173 100644 --- a/tests/baselines/reference/elementAccessChain.symbols +++ b/tests/baselines/reference/elementAccessChain.symbols @@ -97,3 +97,12 @@ o5["b"]?.()["c"].d?.["e"]; >"b" : Symbol(b, Decl(elementAccessChain.ts, 15, 19)) >d : Symbol(d, Decl(elementAccessChain.ts, 15, 32)) +// GH#33744 +declare const o6: () => undefined | ({ x: number }); +>o6 : Symbol(o6, Decl(elementAccessChain.ts, 22, 13)) +>T : Symbol(T, Decl(elementAccessChain.ts, 22, 19)) +>x : Symbol(x, Decl(elementAccessChain.ts, 22, 41)) + +o6()?.["x"]; +>o6 : Symbol(o6, Decl(elementAccessChain.ts, 22, 13)) + diff --git a/tests/baselines/reference/elementAccessChain.types b/tests/baselines/reference/elementAccessChain.types index 0d99166ba0f..a186074e86b 100644 --- a/tests/baselines/reference/elementAccessChain.types +++ b/tests/baselines/reference/elementAccessChain.types @@ -130,3 +130,14 @@ o5["b"]?.()["c"].d?.["e"]; >d : { e: string; } | undefined >"e" : "e" +// GH#33744 +declare const o6: () => undefined | ({ x: number }); +>o6 : () => { x: number; } | undefined +>x : number + +o6()?.["x"]; +>o6()?.["x"] : number | undefined +>o6() : { x: number; } | undefined +>o6 : () => { x: number; } | undefined +>"x" : "x" + diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1.errors.txt b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1.errors.txt index 65eae425bc5..23e68afb156 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1.errors.txt +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(3,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(5,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(7,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(7,30): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(9,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(11,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'm'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(3,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(5,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(7,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. Did you mean to use 'import x from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(7,30): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(9,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. Did you mean to use 'import x from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(11,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'm'. Did you mean to use 'import m from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? ==== tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_0.ts (0 errors) ==== @@ -15,24 +15,24 @@ tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1_1.ts(11,27) var x1: number = defaultBinding1; import defaultBinding2, { a } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? var x1: number = defaultBinding2; import defaultBinding3, { a as b } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? var x1: number = defaultBinding3; import defaultBinding4, { x, a as y } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. Did you mean to use 'import x from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? var x1: number = defaultBinding4; import defaultBinding5, { x as z, } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'x'. Did you mean to use 'import x from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? var x1: number = defaultBinding5; import defaultBinding6, { m, } from "es6ImportDefaultBindingFollowedWithNamedImport1_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'm'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1_0"' has no exported member 'm'. Did you mean to use 'import m from "./es6ImportDefaultBindingFollowedWithNamedImport1_0"' instead? var x1: number = defaultBinding6; \ No newline at end of file diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1InEs5.errors.txt b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1InEs5.errors.txt index b8c06ab3c17..3c73150a195 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1InEs5.errors.txt +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1InEs5.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(3,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(5,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(7,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(7,30): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(9,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. -tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(11,27): error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'm'. +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(3,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(5,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(7,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. Did you mean to use 'import x from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(7,30): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(9,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. Did you mean to use 'import x from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? +tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(11,27): error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'm'. Did you mean to use 'import m from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? ==== tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0.ts (0 errors) ==== @@ -15,24 +15,24 @@ tests/cases/compiler/es6ImportDefaultBindingFollowedWithNamedImport1InEs5_1.ts(1 var x: number = defaultBinding1; import defaultBinding2, { a } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? var x: number = defaultBinding2; import defaultBinding3, { a as b } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? var x: number = defaultBinding3; import defaultBinding4, { x, a as y } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. Did you mean to use 'import x from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'a'. Did you mean to use 'import a from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? var x: number = defaultBinding4; import defaultBinding5, { x as z, } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'x'. Did you mean to use 'import x from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? var x: number = defaultBinding5; import defaultBinding6, { m, } from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"; ~ -!!! error TS2305: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'm'. +!!! error TS2614: Module '"./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' has no exported member 'm'. Did you mean to use 'import m from "./es6ImportDefaultBindingFollowedWithNamedImport1InEs5_0"' instead? var x: number = defaultBinding6; \ No newline at end of file diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1WithExport.errors.txt b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1WithExport.errors.txt index 6d0526d474b..2ab5f14567a 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1WithExport.errors.txt +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImport1WithExport.errors.txt @@ -1,20 +1,20 @@ tests/cases/compiler/client.ts(1,1): error TS1191: An import declaration cannot have modifiers. tests/cases/compiler/client.ts(2,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(3,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(3,34): error TS2305: Module '"./server"' has no exported member 'a'. +tests/cases/compiler/client.ts(3,34): error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? tests/cases/compiler/client.ts(4,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(5,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(5,34): error TS2305: Module '"./server"' has no exported member 'a'. +tests/cases/compiler/client.ts(5,34): error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? tests/cases/compiler/client.ts(6,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(7,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(7,34): error TS2305: Module '"./server"' has no exported member 'x'. -tests/cases/compiler/client.ts(7,37): error TS2305: Module '"./server"' has no exported member 'a'. +tests/cases/compiler/client.ts(7,34): error TS2614: Module '"./server"' has no exported member 'x'. Did you mean to use 'import x from "./server"' instead? +tests/cases/compiler/client.ts(7,37): error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? tests/cases/compiler/client.ts(8,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(9,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(9,34): error TS2305: Module '"./server"' has no exported member 'x'. +tests/cases/compiler/client.ts(9,34): error TS2614: Module '"./server"' has no exported member 'x'. Did you mean to use 'import x from "./server"' instead? tests/cases/compiler/client.ts(10,12): error TS2323: Cannot redeclare exported variable 'x1'. tests/cases/compiler/client.ts(11,1): error TS1191: An import declaration cannot have modifiers. -tests/cases/compiler/client.ts(11,34): error TS2305: Module '"./server"' has no exported member 'm'. +tests/cases/compiler/client.ts(11,34): error TS2614: Module '"./server"' has no exported member 'm'. Did you mean to use 'import m from "./server"' instead? tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported variable 'x1'. @@ -33,7 +33,7 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"./server"' has no exported member 'a'. +!!! error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? export var x1: number = defaultBinding2; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. @@ -41,7 +41,7 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"./server"' has no exported member 'a'. +!!! error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? export var x1: number = defaultBinding3; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. @@ -49,9 +49,9 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"./server"' has no exported member 'x'. +!!! error TS2614: Module '"./server"' has no exported member 'x'. Did you mean to use 'import x from "./server"' instead? ~ -!!! error TS2305: Module '"./server"' has no exported member 'a'. +!!! error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? export var x1: number = defaultBinding4; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. @@ -59,7 +59,7 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"./server"' has no exported member 'x'. +!!! error TS2614: Module '"./server"' has no exported member 'x'. Did you mean to use 'import x from "./server"' instead? export var x1: number = defaultBinding5; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. @@ -67,7 +67,7 @@ tests/cases/compiler/client.ts(12,12): error TS2323: Cannot redeclare exported v ~~~~~~ !!! error TS1191: An import declaration cannot have modifiers. ~ -!!! error TS2305: Module '"./server"' has no exported member 'm'. +!!! error TS2614: Module '"./server"' has no exported member 'm'. Did you mean to use 'import m from "./server"' instead? export var x1: number = defaultBinding6; ~~ !!! error TS2323: Cannot redeclare exported variable 'x1'. diff --git a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportDts1.errors.txt b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportDts1.errors.txt index b2313170af7..682d0198b2e 100644 --- a/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportDts1.errors.txt +++ b/tests/baselines/reference/es6ImportDefaultBindingFollowedWithNamedImportDts1.errors.txt @@ -1,9 +1,9 @@ -tests/cases/compiler/client.ts(3,27): error TS2305: Module '"./server"' has no exported member 'a'. -tests/cases/compiler/client.ts(5,27): error TS2305: Module '"./server"' has no exported member 'a'. -tests/cases/compiler/client.ts(7,27): error TS2305: Module '"./server"' has no exported member 'x'. -tests/cases/compiler/client.ts(7,30): error TS2305: Module '"./server"' has no exported member 'a'. -tests/cases/compiler/client.ts(9,27): error TS2305: Module '"./server"' has no exported member 'x'. -tests/cases/compiler/client.ts(11,27): error TS2305: Module '"./server"' has no exported member 'm'. +tests/cases/compiler/client.ts(3,27): error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? +tests/cases/compiler/client.ts(5,27): error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? +tests/cases/compiler/client.ts(7,27): error TS2614: Module '"./server"' has no exported member 'x'. Did you mean to use 'import x from "./server"' instead? +tests/cases/compiler/client.ts(7,30): error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? +tests/cases/compiler/client.ts(9,27): error TS2614: Module '"./server"' has no exported member 'x'. Did you mean to use 'import x from "./server"' instead? +tests/cases/compiler/client.ts(11,27): error TS2614: Module '"./server"' has no exported member 'm'. Did you mean to use 'import m from "./server"' instead? ==== tests/cases/compiler/server.ts (0 errors) ==== @@ -15,23 +15,23 @@ tests/cases/compiler/client.ts(11,27): error TS2305: Module '"./server"' has no export var x1 = new defaultBinding1(); import defaultBinding2, { a } from "./server"; ~ -!!! error TS2305: Module '"./server"' has no exported member 'a'. +!!! error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? export var x2 = new defaultBinding2(); import defaultBinding3, { a as b } from "./server"; ~ -!!! error TS2305: Module '"./server"' has no exported member 'a'. +!!! error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? export var x3 = new defaultBinding3(); import defaultBinding4, { x, a as y } from "./server"; ~ -!!! error TS2305: Module '"./server"' has no exported member 'x'. +!!! error TS2614: Module '"./server"' has no exported member 'x'. Did you mean to use 'import x from "./server"' instead? ~ -!!! error TS2305: Module '"./server"' has no exported member 'a'. +!!! error TS2614: Module '"./server"' has no exported member 'a'. Did you mean to use 'import a from "./server"' instead? export var x4 = new defaultBinding4(); import defaultBinding5, { x as z, } from "./server"; ~ -!!! error TS2305: Module '"./server"' has no exported member 'x'. +!!! error TS2614: Module '"./server"' has no exported member 'x'. Did you mean to use 'import x from "./server"' instead? export var x5 = new defaultBinding5(); import defaultBinding6, { m, } from "./server"; ~ -!!! error TS2305: Module '"./server"' has no exported member 'm'. +!!! error TS2614: Module '"./server"' has no exported member 'm'. Did you mean to use 'import m from "./server"' instead? export var x6 = new defaultBinding6(); \ No newline at end of file diff --git a/tests/baselines/reference/fallFromLastCase2.errors.txt b/tests/baselines/reference/fallFromLastCase2.errors.txt index fcf3251ac3f..5800e4c7d88 100644 --- a/tests/baselines/reference/fallFromLastCase2.errors.txt +++ b/tests/baselines/reference/fallFromLastCase2.errors.txt @@ -11,7 +11,7 @@ tests/cases/compiler/fallFromLastCase2.ts(21,9): error TS7029: Fallthrough case use("1"); break; case 2: - ~~~~ + ~~~~~~~ !!! error TS7029: Fallthrough case in switch. use("2"); case 3: @@ -26,7 +26,7 @@ tests/cases/compiler/fallFromLastCase2.ts(21,9): error TS7029: Fallthrough case use("1"); break; default: - ~~~~~~~ + ~~~~~~~~ !!! error TS7029: Fallthrough case in switch. use("2"); case 2: diff --git a/tests/baselines/reference/genericIndexTypeHasSensibleErrorMessage.errors.txt b/tests/baselines/reference/genericIndexTypeHasSensibleErrorMessage.errors.txt index ebcfc8d1482..36f2bf9fbda 100644 --- a/tests/baselines/reference/genericIndexTypeHasSensibleErrorMessage.errors.txt +++ b/tests/baselines/reference/genericIndexTypeHasSensibleErrorMessage.errors.txt @@ -1,7 +1,7 @@ -tests/cases/compiler/genericIndexTypeHasSensibleErrorMessage.ts(1,33): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/genericIndexTypeHasSensibleErrorMessage.ts(1,33): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/compiler/genericIndexTypeHasSensibleErrorMessage.ts (1 errors) ==== type Wat = { [x: T]: string }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. \ No newline at end of file +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.d.errors.txt b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.d.errors.txt index 2f6db48bf2f..14107cde7e1 100644 --- a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.d.errors.txt +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.d.errors.txt @@ -2,7 +2,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(10,21): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(11,22): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(11,26): error TS2314: Generic type 'C' requires 1 type argument(s). -tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(12,19): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(12,19): error TS1023: An index signature parameter type must be either 'string' or 'number'. tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(12,22): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(12,26): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.d.ts(14,23): error TS2314: Generic type 'C' requires 1 type argument(s). @@ -36,7 +36,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc !!! error TS2314: Generic type 'C' requires 1 type argument(s). declare var d: { [x: C]: C }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. ~ !!! error TS2314: Generic type 'C' requires 1 type argument(s). ~ diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.errors.txt b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.errors.txt index d57f3c2fc0d..68d91622a31 100644 --- a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.errors.txt +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument.errors.txt @@ -2,7 +2,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.ts(10,13): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.ts(11,14): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.ts(11,18): error TS2314: Generic type 'C' requires 1 type argument(s). -tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.ts(12,11): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.ts(12,11): error TS1023: An index signature parameter type must be either 'string' or 'number'. tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.ts(12,14): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.ts(12,18): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument.ts(14,13): error TS2314: Generic type 'C' requires 1 type argument(s). @@ -46,7 +46,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc !!! error TS2314: Generic type 'C' requires 1 type argument(s). var d: { [x: C]: C }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. ~ !!! error TS2314: Generic type 'C' requires 1 type argument(s). ~ diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.errors.txt b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.errors.txt index 276654562a1..7a63caeaf67 100644 --- a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.errors.txt +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument2.errors.txt @@ -2,7 +2,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(10,13): error TS2314: Generic type 'I' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(11,14): error TS2314: Generic type 'I' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(11,18): error TS2314: Generic type 'I' requires 1 type argument(s). -tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(12,11): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(12,11): error TS1023: An index signature parameter type must be either 'string' or 'number'. tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(12,14): error TS2314: Generic type 'I' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(12,18): error TS2314: Generic type 'I' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument2.ts(14,13): error TS2314: Generic type 'I' requires 1 type argument(s). @@ -46,7 +46,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc !!! error TS2314: Generic type 'I' requires 1 type argument(s). var d: { [x: I]: I }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. ~ !!! error TS2314: Generic type 'I' requires 1 type argument(s). ~ diff --git a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.errors.txt b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.errors.txt index 95857c925be..bb6ee2494ad 100644 --- a/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.errors.txt +++ b/tests/baselines/reference/genericTypeReferenceWithoutTypeArgument3.errors.txt @@ -2,7 +2,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(10,21): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(11,22): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(11,26): error TS2314: Generic type 'C' requires 1 type argument(s). -tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(12,19): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(12,19): error TS1023: An index signature parameter type must be either 'string' or 'number'. tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(12,22): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(12,26): error TS2314: Generic type 'C' requires 1 type argument(s). tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenceWithoutTypeArgument3.ts(14,23): error TS2314: Generic type 'C' requires 1 type argument(s). @@ -36,7 +36,7 @@ tests/cases/conformance/types/specifyingTypes/typeReferences/genericTypeReferenc !!! error TS2314: Generic type 'C' requires 1 type argument(s). declare var d: { [x: C]: C }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. ~ !!! error TS2314: Generic type 'C' requires 1 type argument(s). ~ diff --git a/tests/baselines/reference/globalThisGlobalExportAsGlobal.errors.txt b/tests/baselines/reference/globalThisGlobalExportAsGlobal.errors.txt new file mode 100644 index 00000000000..3b9d75e466e --- /dev/null +++ b/tests/baselines/reference/globalThisGlobalExportAsGlobal.errors.txt @@ -0,0 +1,14 @@ +tests/cases/conformance/es2019/globalThisGlobalExportAsGlobal.ts(2,9): error TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations. +tests/cases/conformance/es2019/globalThisGlobalExportAsGlobal.ts(3,14): error TS2661: Cannot export 'globalThis'. Only local declarations can be exported from a module. + + +==== tests/cases/conformance/es2019/globalThisGlobalExportAsGlobal.ts (2 errors) ==== + // https://github.com/microsoft/TypeScript/issues/33754 + declare global { + ~~~~~~ +!!! error TS2669: Augmentations for the global scope can only be directly nested in external modules or ambient module declarations. + export { globalThis as global } + ~~~~~~~~~~ +!!! error TS2661: Cannot export 'globalThis'. Only local declarations can be exported from a module. + } + \ No newline at end of file diff --git a/tests/baselines/reference/globalThisGlobalExportAsGlobal.js b/tests/baselines/reference/globalThisGlobalExportAsGlobal.js new file mode 100644 index 00000000000..4df230e1151 --- /dev/null +++ b/tests/baselines/reference/globalThisGlobalExportAsGlobal.js @@ -0,0 +1,8 @@ +//// [globalThisGlobalExportAsGlobal.ts] +// https://github.com/microsoft/TypeScript/issues/33754 +declare global { + export { globalThis as global } +} + + +//// [globalThisGlobalExportAsGlobal.js] diff --git a/tests/baselines/reference/globalThisGlobalExportAsGlobal.symbols b/tests/baselines/reference/globalThisGlobalExportAsGlobal.symbols new file mode 100644 index 00000000000..49ac97e912a --- /dev/null +++ b/tests/baselines/reference/globalThisGlobalExportAsGlobal.symbols @@ -0,0 +1,10 @@ +=== tests/cases/conformance/es2019/globalThisGlobalExportAsGlobal.ts === +// https://github.com/microsoft/TypeScript/issues/33754 +declare global { +>global : Symbol(global, Decl(globalThisGlobalExportAsGlobal.ts, 0, 0)) + + export { globalThis as global } +>globalThis : Symbol(globalThis) +>global : Symbol(global, Decl(globalThisGlobalExportAsGlobal.ts, 2, 12)) +} + diff --git a/tests/baselines/reference/globalThisGlobalExportAsGlobal.types b/tests/baselines/reference/globalThisGlobalExportAsGlobal.types new file mode 100644 index 00000000000..68867496daf --- /dev/null +++ b/tests/baselines/reference/globalThisGlobalExportAsGlobal.types @@ -0,0 +1,10 @@ +=== tests/cases/conformance/es2019/globalThisGlobalExportAsGlobal.ts === +// https://github.com/microsoft/TypeScript/issues/33754 +declare global { +>global : typeof global + + export { globalThis as global } +>globalThis : typeof globalThis +>global : typeof globalThis +} + diff --git a/tests/baselines/reference/importAliasModuleExports.errors.txt b/tests/baselines/reference/importAliasModuleExports.errors.txt new file mode 100644 index 00000000000..ea3dd9ef0e0 --- /dev/null +++ b/tests/baselines/reference/importAliasModuleExports.errors.txt @@ -0,0 +1,20 @@ +tests/cases/conformance/salsa/main.js(2,13): error TS2339: Property 'foo' does not exist on type 'Alias'. +tests/cases/conformance/salsa/main.js(4,9): error TS2339: Property 'foo' does not exist on type 'Alias'. + + +==== tests/cases/conformance/salsa/mod1.js (0 errors) ==== + class Alias { + bar() { return 1 } + } + module.exports = Alias; + +==== tests/cases/conformance/salsa/main.js (2 errors) ==== + import A from './mod1' + A.prototype.foo = 0 + ~~~ +!!! error TS2339: Property 'foo' does not exist on type 'Alias'. + new A().bar + new A().foo + ~~~ +!!! error TS2339: Property 'foo' does not exist on type 'Alias'. + \ No newline at end of file diff --git a/tests/baselines/reference/importAliasModuleExports.symbols b/tests/baselines/reference/importAliasModuleExports.symbols new file mode 100644 index 00000000000..4ab081d608f --- /dev/null +++ b/tests/baselines/reference/importAliasModuleExports.symbols @@ -0,0 +1,30 @@ +=== tests/cases/conformance/salsa/mod1.js === +class Alias { +>Alias : Symbol(Alias, Decl(mod1.js, 0, 0)) + + bar() { return 1 } +>bar : Symbol(Alias.bar, Decl(mod1.js, 0, 13)) +} +module.exports = Alias; +>module.exports : Symbol("tests/cases/conformance/salsa/mod1", Decl(mod1.js, 0, 0)) +>module : Symbol(export=, Decl(mod1.js, 2, 1)) +>exports : Symbol(export=, Decl(mod1.js, 2, 1)) +>Alias : Symbol(Alias, Decl(mod1.js, 0, 0)) + +=== tests/cases/conformance/salsa/main.js === +import A from './mod1' +>A : Symbol(A, Decl(main.js, 0, 6)) + +A.prototype.foo = 0 +>A.prototype : Symbol(A.prototype) +>A : Symbol(A, Decl(main.js, 0, 6)) +>prototype : Symbol(A.prototype) + +new A().bar +>new A().bar : Symbol(A.bar, Decl(mod1.js, 0, 13)) +>A : Symbol(A, Decl(main.js, 0, 6)) +>bar : Symbol(A.bar, Decl(mod1.js, 0, 13)) + +new A().foo +>A : Symbol(A, Decl(main.js, 0, 6)) + diff --git a/tests/baselines/reference/importAliasModuleExports.types b/tests/baselines/reference/importAliasModuleExports.types new file mode 100644 index 00000000000..1303ba6e8c4 --- /dev/null +++ b/tests/baselines/reference/importAliasModuleExports.types @@ -0,0 +1,40 @@ +=== tests/cases/conformance/salsa/mod1.js === +class Alias { +>Alias : Alias + + bar() { return 1 } +>bar : () => number +>1 : 1 +} +module.exports = Alias; +>module.exports = Alias : typeof Alias +>module.exports : typeof Alias +>module : { "tests/cases/conformance/salsa/mod1": typeof Alias; } +>exports : typeof Alias +>Alias : typeof Alias + +=== tests/cases/conformance/salsa/main.js === +import A from './mod1' +>A : typeof A + +A.prototype.foo = 0 +>A.prototype.foo = 0 : 0 +>A.prototype.foo : any +>A.prototype : A +>A : typeof A +>prototype : A +>foo : any +>0 : 0 + +new A().bar +>new A().bar : () => number +>new A() : A +>A : typeof A +>bar : () => number + +new A().foo +>new A().foo : any +>new A() : A +>A : typeof A +>foo : any + diff --git a/tests/baselines/reference/importCallExpressionErrorInES2015.errors.txt b/tests/baselines/reference/importCallExpressionErrorInES2015.errors.txt index b2000f9319e..b071d82ccb1 100644 --- a/tests/baselines/reference/importCallExpressionErrorInES2015.errors.txt +++ b/tests/baselines/reference/importCallExpressionErrorInES2015.errors.txt @@ -1,6 +1,6 @@ -tests/cases/conformance/dynamicImport/1.ts(1,1): error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. -tests/cases/conformance/dynamicImport/1.ts(2,10): error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. -tests/cases/conformance/dynamicImport/1.ts(8,16): error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +tests/cases/conformance/dynamicImport/1.ts(1,1): error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. +tests/cases/conformance/dynamicImport/1.ts(2,10): error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. +tests/cases/conformance/dynamicImport/1.ts(8,16): error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. ==== tests/cases/conformance/dynamicImport/0.ts (0 errors) ==== @@ -9,10 +9,10 @@ tests/cases/conformance/dynamicImport/1.ts(8,16): error TS1323: Dynamic import i ==== tests/cases/conformance/dynamicImport/1.ts (3 errors) ==== import("./0"); ~~~~~~~~~~~~~ -!!! error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +!!! error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. var p1 = import("./0"); ~~~~~~~~~~~~~ -!!! error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +!!! error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. p1.then(zero => { return zero.foo(); }) @@ -20,5 +20,5 @@ tests/cases/conformance/dynamicImport/1.ts(8,16): error TS1323: Dynamic import i function foo() { const p2 = import("./0"); ~~~~~~~~~~~~~ -!!! error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +!!! error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. } \ No newline at end of file diff --git a/tests/baselines/reference/importCallExpressionNestedES2015.errors.txt b/tests/baselines/reference/importCallExpressionNestedES2015.errors.txt index ef1a96ee913..abb70024393 100644 --- a/tests/baselines/reference/importCallExpressionNestedES2015.errors.txt +++ b/tests/baselines/reference/importCallExpressionNestedES2015.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/dynamicImport/index.ts(2,18): error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. -tests/cases/conformance/dynamicImport/index.ts(2,32): error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +tests/cases/conformance/dynamicImport/index.ts(2,18): error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. +tests/cases/conformance/dynamicImport/index.ts(2,32): error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. ==== tests/cases/conformance/dynamicImport/foo.ts (0 errors) ==== @@ -9,7 +9,7 @@ tests/cases/conformance/dynamicImport/index.ts(2,32): error TS1323: Dynamic impo async function foo() { return await import((await import("./foo")).default); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +!!! error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. ~~~~~~~~~~~~~~~ -!!! error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +!!! error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. } \ No newline at end of file diff --git a/tests/baselines/reference/importCallExpressionNestedES20152.errors.txt b/tests/baselines/reference/importCallExpressionNestedES20152.errors.txt index ef1a96ee913..abb70024393 100644 --- a/tests/baselines/reference/importCallExpressionNestedES20152.errors.txt +++ b/tests/baselines/reference/importCallExpressionNestedES20152.errors.txt @@ -1,5 +1,5 @@ -tests/cases/conformance/dynamicImport/index.ts(2,18): error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. -tests/cases/conformance/dynamicImport/index.ts(2,32): error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +tests/cases/conformance/dynamicImport/index.ts(2,18): error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. +tests/cases/conformance/dynamicImport/index.ts(2,32): error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. ==== tests/cases/conformance/dynamicImport/foo.ts (0 errors) ==== @@ -9,7 +9,7 @@ tests/cases/conformance/dynamicImport/index.ts(2,32): error TS1323: Dynamic impo async function foo() { return await import((await import("./foo")).default); ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -!!! error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +!!! error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. ~~~~~~~~~~~~~~~ -!!! error TS1323: Dynamic import is only supported when '--module' flag is 'commonjs' or 'esNext'. +!!! error TS1323: Dynamic imports are only supported when the '--module' flag is set to 'esnext', 'commonjs', 'amd', 'system', or 'umd'. } \ No newline at end of file diff --git a/tests/baselines/reference/indexTypeCheck.errors.txt b/tests/baselines/reference/indexTypeCheck.errors.txt index 9d839e9eb30..c5c16f5ecd9 100644 --- a/tests/baselines/reference/indexTypeCheck.errors.txt +++ b/tests/baselines/reference/indexTypeCheck.errors.txt @@ -4,7 +4,7 @@ tests/cases/compiler/indexTypeCheck.ts(17,2): error TS2413: Numeric index type ' tests/cases/compiler/indexTypeCheck.ts(22,2): error TS2413: Numeric index type 'Orange' is not assignable to string index type 'Yellow'. tests/cases/compiler/indexTypeCheck.ts(27,2): error TS2413: Numeric index type 'number' is not assignable to string index type 'string'. tests/cases/compiler/indexTypeCheck.ts(32,3): error TS1096: An index signature must have exactly one parameter. -tests/cases/compiler/indexTypeCheck.ts(36,3): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/indexTypeCheck.ts(36,3): error TS1023: An index signature parameter type must be either 'string' or 'number'. tests/cases/compiler/indexTypeCheck.ts(51,8): error TS2538: Type 'Blue' cannot be used as an index type. @@ -58,7 +58,7 @@ tests/cases/compiler/indexTypeCheck.ts(51,8): error TS2538: Type 'Blue' cannot b interface Magenta { [p:Purple]; // error ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } var yellow: Yellow; diff --git a/tests/baselines/reference/indexerConstraints2.errors.txt b/tests/baselines/reference/indexerConstraints2.errors.txt index aca2af28adc..b3bd692122e 100644 --- a/tests/baselines/reference/indexerConstraints2.errors.txt +++ b/tests/baselines/reference/indexerConstraints2.errors.txt @@ -3,11 +3,11 @@ tests/cases/compiler/indexerConstraints2.ts(17,5): error TS2413: Numeric index t tests/cases/compiler/indexerConstraints2.ts(26,5): error TS2413: Numeric index type 'A' is not assignable to string index type 'B'. tests/cases/compiler/indexerConstraints2.ts(34,6): error TS1336: An index signature parameter type cannot be a type alias. Consider writing '[n: number]: A' instead. tests/cases/compiler/indexerConstraints2.ts(40,6): error TS1336: An index signature parameter type cannot be a type alias. Consider writing '[s: string]: A' instead. -tests/cases/compiler/indexerConstraints2.ts(46,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/indexerConstraints2.ts(46,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. tests/cases/compiler/indexerConstraints2.ts(52,6): error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead. -tests/cases/compiler/indexerConstraints2.ts(58,6): error TS1023: An index signature parameter type must be 'string' or 'number'. -tests/cases/compiler/indexerConstraints2.ts(64,6): error TS1023: An index signature parameter type must be 'string' or 'number'. -tests/cases/compiler/indexerConstraints2.ts(70,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/compiler/indexerConstraints2.ts(58,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. +tests/cases/compiler/indexerConstraints2.ts(64,6): error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead. +tests/cases/compiler/indexerConstraints2.ts(70,6): error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead. tests/cases/compiler/indexerConstraints2.ts(74,6): error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead. tests/cases/compiler/indexerConstraints2.ts(79,6): error TS1336: An index signature parameter type cannot be a type alias. Consider writing '[key: string]: any' instead. @@ -70,7 +70,7 @@ tests/cases/compiler/indexerConstraints2.ts(79,6): error TS1336: An index signat interface N { [b: AliasedBoolean]: A; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } type IndexableUnion = "foo" | "bar"; @@ -86,7 +86,7 @@ tests/cases/compiler/indexerConstraints2.ts(79,6): error TS1336: An index signat interface P { [u: NonIndexableUnion]: A; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } type NonIndexableUnion2 = string | number; @@ -94,7 +94,7 @@ tests/cases/compiler/indexerConstraints2.ts(79,6): error TS1336: An index signat interface Q { [u: NonIndexableUnion2]: A; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead. } type NonIndexableUnion3 = "foo" | 42; @@ -102,7 +102,7 @@ tests/cases/compiler/indexerConstraints2.ts(79,6): error TS1336: An index signat interface R { [u: NonIndexableUnion3]: A; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1337: An index signature parameter type cannot be a union type. Consider using a mapped object type instead. } interface S { diff --git a/tests/baselines/reference/inheritanceMemberPropertyOverridingMethod.errors.txt b/tests/baselines/reference/inheritanceMemberPropertyOverridingMethod.errors.txt deleted file mode 100644 index 2b56866b22b..00000000000 --- a/tests/baselines/reference/inheritanceMemberPropertyOverridingMethod.errors.txt +++ /dev/null @@ -1,15 +0,0 @@ -tests/cases/compiler/inheritanceMemberPropertyOverridingMethod.ts(8,5): error TS2424: Class 'a' defines instance member function 'x', but extended class 'b' defines it as instance member property. - - -==== tests/cases/compiler/inheritanceMemberPropertyOverridingMethod.ts (1 errors) ==== - class a { - x() { - return "20"; - } - } - - class b extends a { - x: () => string; - ~ -!!! error TS2424: Class 'a' defines instance member function 'x', but extended class 'b' defines it as instance member property. - } \ No newline at end of file diff --git a/tests/baselines/reference/instanceMemberWithComputedPropertyName2.js b/tests/baselines/reference/instanceMemberWithComputedPropertyName2.js new file mode 100644 index 00000000000..9ca393c6f01 --- /dev/null +++ b/tests/baselines/reference/instanceMemberWithComputedPropertyName2.js @@ -0,0 +1,25 @@ +//// [instanceMemberWithComputedPropertyName2.ts] +// https://github.com/microsoft/TypeScript/issues/33857 +"use strict"; +const x = 1; +class C { + [x]: string; +} + + +//// [instanceMemberWithComputedPropertyName2.js] +// https://github.com/microsoft/TypeScript/issues/33857 +"use strict"; +var _a; +const x = 1; +class C { + constructor() { + Object.defineProperty(this, _a, { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + } +} +_a = x; diff --git a/tests/baselines/reference/instanceMemberWithComputedPropertyName2.symbols b/tests/baselines/reference/instanceMemberWithComputedPropertyName2.symbols new file mode 100644 index 00000000000..744a1d089de --- /dev/null +++ b/tests/baselines/reference/instanceMemberWithComputedPropertyName2.symbols @@ -0,0 +1,14 @@ +=== tests/cases/conformance/classes/propertyMemberDeclarations/instanceMemberWithComputedPropertyName2.ts === +// https://github.com/microsoft/TypeScript/issues/33857 +"use strict"; +const x = 1; +>x : Symbol(x, Decl(instanceMemberWithComputedPropertyName2.ts, 2, 5)) + +class C { +>C : Symbol(C, Decl(instanceMemberWithComputedPropertyName2.ts, 2, 12)) + + [x]: string; +>[x] : Symbol(C[x], Decl(instanceMemberWithComputedPropertyName2.ts, 3, 9)) +>x : Symbol(x, Decl(instanceMemberWithComputedPropertyName2.ts, 2, 5)) +} + diff --git a/tests/baselines/reference/instanceMemberWithComputedPropertyName2.types b/tests/baselines/reference/instanceMemberWithComputedPropertyName2.types new file mode 100644 index 00000000000..1727f88cb5c --- /dev/null +++ b/tests/baselines/reference/instanceMemberWithComputedPropertyName2.types @@ -0,0 +1,17 @@ +=== tests/cases/conformance/classes/propertyMemberDeclarations/instanceMemberWithComputedPropertyName2.ts === +// https://github.com/microsoft/TypeScript/issues/33857 +"use strict"; +>"use strict" : "use strict" + +const x = 1; +>x : 1 +>1 : 1 + +class C { +>C : C + + [x]: string; +>[x] : string +>x : 1 +} + diff --git a/tests/baselines/reference/javascriptDefinePropertyPrototypeNonConstructor.symbols b/tests/baselines/reference/javascriptDefinePropertyPrototypeNonConstructor.symbols new file mode 100644 index 00000000000..db4aaca770c --- /dev/null +++ b/tests/baselines/reference/javascriptDefinePropertyPrototypeNonConstructor.symbols @@ -0,0 +1,23 @@ +=== /a.js === +function Graphic() { +>Graphic : Symbol(Graphic, Decl(a.js, 0, 0)) +} + +Object.defineProperty(Graphic.prototype, "instance", { +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Graphic.prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>Graphic : Symbol(Graphic, Decl(a.js, 0, 0)) +>prototype : Symbol(Function.prototype, Decl(lib.es5.d.ts, --, --)) +>"instance" : Symbol(Graphic.instance, Decl(a.js, 1, 1)) + + get: function() { +>get : Symbol(get, Decl(a.js, 3, 54)) + + return this; +>this : Symbol(Graphic, Decl(a.js, 0, 0)) + } +}); + + diff --git a/tests/baselines/reference/javascriptDefinePropertyPrototypeNonConstructor.types b/tests/baselines/reference/javascriptDefinePropertyPrototypeNonConstructor.types new file mode 100644 index 00000000000..9c873b65d08 --- /dev/null +++ b/tests/baselines/reference/javascriptDefinePropertyPrototypeNonConstructor.types @@ -0,0 +1,26 @@ +=== /a.js === +function Graphic() { +>Graphic : typeof Graphic +} + +Object.defineProperty(Graphic.prototype, "instance", { +>Object.defineProperty(Graphic.prototype, "instance", { get: function() { return this; }}) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Graphic.prototype : any +>Graphic : typeof Graphic +>prototype : any +>"instance" : "instance" +>{ get: function() { return this; }} : { get: () => this; } + + get: function() { +>get : () => this +>function() { return this; } : () => this + + return this; +>this : this + } +}); + + diff --git a/tests/baselines/reference/javascriptImportDefaultBadExport.errors.txt b/tests/baselines/reference/javascriptImportDefaultBadExport.errors.txt new file mode 100644 index 00000000000..71ff85e2155 --- /dev/null +++ b/tests/baselines/reference/javascriptImportDefaultBadExport.errors.txt @@ -0,0 +1,16 @@ +/b.js(1,8): error TS1259: Module '"/a"' can only be default-imported using the 'esModuleInterop' flag + + +==== /a.js (0 errors) ==== + // https://github.com/microsoft/TypeScript/issues/34481 + + + const alias = {}; + module.exports = alias; + +==== /b.js (1 errors) ==== + import a from "./a"; + ~ +!!! error TS1259: Module '"/a"' can only be default-imported using the 'esModuleInterop' flag +!!! related TS2594 /a.js:5:1: This module is declared with using 'export =', and can only be used with a default import when using the 'esModuleInterop' flag. + \ No newline at end of file diff --git a/tests/baselines/reference/javascriptImportDefaultBadExport.symbols b/tests/baselines/reference/javascriptImportDefaultBadExport.symbols new file mode 100644 index 00000000000..b5506996aff --- /dev/null +++ b/tests/baselines/reference/javascriptImportDefaultBadExport.symbols @@ -0,0 +1,17 @@ +=== /a.js === +// https://github.com/microsoft/TypeScript/issues/34481 + + +const alias = {}; +>alias : Symbol(alias, Decl(a.js, 3, 5)) + +module.exports = alias; +>module.exports : Symbol("/a", Decl(a.js, 0, 0)) +>module : Symbol(export=, Decl(a.js, 3, 17)) +>exports : Symbol(export=, Decl(a.js, 3, 17)) +>alias : Symbol(alias, Decl(a.js, 3, 5)) + +=== /b.js === +import a from "./a"; +>a : Symbol(a, Decl(b.js, 0, 6)) + diff --git a/tests/baselines/reference/javascriptImportDefaultBadExport.types b/tests/baselines/reference/javascriptImportDefaultBadExport.types new file mode 100644 index 00000000000..81d68cbdf96 --- /dev/null +++ b/tests/baselines/reference/javascriptImportDefaultBadExport.types @@ -0,0 +1,19 @@ +=== /a.js === +// https://github.com/microsoft/TypeScript/issues/34481 + + +const alias = {}; +>alias : {} +>{} : {} + +module.exports = alias; +>module.exports = alias : {} +>module.exports : {} +>module : { "/a": {}; } +>exports : {} +>alias : {} + +=== /b.js === +import a from "./a"; +>a : any + diff --git a/tests/baselines/reference/jsCheckObjectDefineThisNoCrash.errors.txt b/tests/baselines/reference/jsCheckObjectDefineThisNoCrash.errors.txt new file mode 100644 index 00000000000..cc6c7e7f0d7 --- /dev/null +++ b/tests/baselines/reference/jsCheckObjectDefineThisNoCrash.errors.txt @@ -0,0 +1,13 @@ +tests/cases/compiler/jsCheckObjectDefineThisNoCrash.js(5,36): error TS2339: Property '_prop' does not exist on type 'C'. + + +==== tests/cases/compiler/jsCheckObjectDefineThisNoCrash.js (1 errors) ==== + class C { + constructor() { + // Neither of the following should be recognized as declarations yet + Object.defineProperty(this, "_prop", { value: {} }); + Object.defineProperty(this._prop, "num", { value: 12 }); + ~~~~~ +!!! error TS2339: Property '_prop' does not exist on type 'C'. + } + } \ No newline at end of file diff --git a/tests/baselines/reference/jsCheckObjectDefineThisNoCrash.symbols b/tests/baselines/reference/jsCheckObjectDefineThisNoCrash.symbols new file mode 100644 index 00000000000..f15fec2005b --- /dev/null +++ b/tests/baselines/reference/jsCheckObjectDefineThisNoCrash.symbols @@ -0,0 +1,21 @@ +=== tests/cases/compiler/jsCheckObjectDefineThisNoCrash.js === +class C { +>C : Symbol(C, Decl(jsCheckObjectDefineThisNoCrash.js, 0, 0)) + + constructor() { + // Neither of the following should be recognized as declarations yet + Object.defineProperty(this, "_prop", { value: {} }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>this : Symbol(C, Decl(jsCheckObjectDefineThisNoCrash.js, 0, 0)) +>value : Symbol(value, Decl(jsCheckObjectDefineThisNoCrash.js, 3, 46)) + + Object.defineProperty(this._prop, "num", { value: 12 }); +>Object.defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>Object : Symbol(Object, Decl(lib.es5.d.ts, --, --), Decl(lib.es5.d.ts, --, --)) +>defineProperty : Symbol(ObjectConstructor.defineProperty, Decl(lib.es5.d.ts, --, --)) +>this : Symbol(C, Decl(jsCheckObjectDefineThisNoCrash.js, 0, 0)) +>value : Symbol(value, Decl(jsCheckObjectDefineThisNoCrash.js, 4, 50)) + } +} diff --git a/tests/baselines/reference/jsCheckObjectDefineThisNoCrash.types b/tests/baselines/reference/jsCheckObjectDefineThisNoCrash.types new file mode 100644 index 00000000000..5b771cb5142 --- /dev/null +++ b/tests/baselines/reference/jsCheckObjectDefineThisNoCrash.types @@ -0,0 +1,31 @@ +=== tests/cases/compiler/jsCheckObjectDefineThisNoCrash.js === +class C { +>C : C + + constructor() { + // Neither of the following should be recognized as declarations yet + Object.defineProperty(this, "_prop", { value: {} }); +>Object.defineProperty(this, "_prop", { value: {} }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>this : this +>"_prop" : "_prop" +>{ value: {} } : { value: {}; } +>value : {} +>{} : {} + + Object.defineProperty(this._prop, "num", { value: 12 }); +>Object.defineProperty(this._prop, "num", { value: 12 }) : any +>Object.defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>Object : ObjectConstructor +>defineProperty : (o: any, p: string | number | symbol, attributes: PropertyDescriptor & ThisType) => any +>this._prop : any +>this : this +>_prop : any +>"num" : "num" +>{ value: 12 } : { value: number; } +>value : number +>12 : 12 + } +} diff --git a/tests/baselines/reference/jsDeclarationsFunctions.js b/tests/baselines/reference/jsDeclarationsFunctions.js index c80fe43a1d2..23f300e2a14 100644 --- a/tests/baselines/reference/jsDeclarationsFunctions.js +++ b/tests/baselines/reference/jsDeclarationsFunctions.js @@ -130,8 +130,6 @@ export namespace b { export function c(): void; export namespace c { export { Cls }; - class Cls { - } } /** * @param {number} a @@ -156,6 +154,8 @@ export namespace f { } export function i(): void; export function j(): void; +declare class Cls { +} /** * @param {{x: string}} a * @param {{y: typeof b}} b diff --git a/tests/baselines/reference/jsFileCompilationBindReachabilityErrors.errors.txt b/tests/baselines/reference/jsFileCompilationBindReachabilityErrors.errors.txt index c2c572aa304..efd505800d9 100644 --- a/tests/baselines/reference/jsFileCompilationBindReachabilityErrors.errors.txt +++ b/tests/baselines/reference/jsFileCompilationBindReachabilityErrors.errors.txt @@ -7,7 +7,7 @@ tests/cases/compiler/a.js(19,1): error TS7028: Unused label. function foo(a, b) { switch (a) { case 10: - ~~~~ + ~~~~~~~~ !!! error TS7029: Fallthrough case in switch. if (b) { return b; diff --git a/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt b/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt index b3298f137f1..5392d51114c 100644 --- a/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt +++ b/tests/baselines/reference/jsdocTypeNongenericInstantiationAttempt.errors.txt @@ -5,7 +5,6 @@ tests/cases/compiler/index4.js(2,19): error TS2315: Type 'Function' is not gener tests/cases/compiler/index5.js(2,19): error TS2315: Type 'String' is not generic. tests/cases/compiler/index6.js(2,19): error TS2315: Type 'Number' is not generic. tests/cases/compiler/index7.js(2,19): error TS2315: Type 'Object' is not generic. -tests/cases/compiler/index8.js(4,12): error TS2749: 'fn' refers to a value, but is being used as a type here. tests/cases/compiler/index8.js(4,15): error TS2304: Cannot find name 'T'. @@ -84,13 +83,11 @@ tests/cases/compiler/index8.js(4,15): error TS2304: Cannot find name 'T'. return 'Hello ' + somebody; } -==== tests/cases/compiler/index8.js (2 errors) ==== +==== tests/cases/compiler/index8.js (1 errors) ==== function fn() {} /** * @param {fn} somebody - ~~ -!!! error TS2749: 'fn' refers to a value, but is being used as a type here. ~ !!! error TS2304: Cannot find name 'T'. */ diff --git a/tests/baselines/reference/jsdocTypeReferenceExports.errors.txt b/tests/baselines/reference/jsdocTypeReferenceExports.errors.txt deleted file mode 100644 index 48d0321be71..00000000000 --- a/tests/baselines/reference/jsdocTypeReferenceExports.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/conformance/jsdoc/bug27342.js(3,11): error TS2709: Cannot use namespace 'exports' as a type. - - -==== tests/cases/conformance/jsdoc/bug27342.js (1 errors) ==== - module.exports = {} - /** - * @type {exports} - ~~~~~~~ -!!! error TS2709: Cannot use namespace 'exports' as a type. - */ - var x - - \ No newline at end of file diff --git a/tests/baselines/reference/jsdocTypeReferenceToValue.symbols b/tests/baselines/reference/jsdocTypeReferenceToValue.symbols new file mode 100644 index 00000000000..58facc1e821 --- /dev/null +++ b/tests/baselines/reference/jsdocTypeReferenceToValue.symbols @@ -0,0 +1,10 @@ +=== tests/cases/conformance/jsdoc/foo.js === +/** @param {Image} image */ +function process(image) { +>process : Symbol(process, Decl(foo.js, 0, 0)) +>image : Symbol(image, Decl(foo.js, 1, 17)) + + return new image(1, 1) +>image : Symbol(image, Decl(foo.js, 1, 17)) +} + diff --git a/tests/baselines/reference/jsdocTypeReferenceToValue.types b/tests/baselines/reference/jsdocTypeReferenceToValue.types new file mode 100644 index 00000000000..91f8e26d35d --- /dev/null +++ b/tests/baselines/reference/jsdocTypeReferenceToValue.types @@ -0,0 +1,13 @@ +=== tests/cases/conformance/jsdoc/foo.js === +/** @param {Image} image */ +function process(image) { +>process : (image: new (width?: number, height?: number) => HTMLImageElement) => HTMLImageElement +>image : new (width?: number, height?: number) => HTMLImageElement + + return new image(1, 1) +>new image(1, 1) : HTMLImageElement +>image : new (width?: number, height?: number) => HTMLImageElement +>1 : 1 +>1 : 1 +} + diff --git a/tests/baselines/reference/jsxDeclarationsWithEsModuleInteropNoCrash.js b/tests/baselines/reference/jsxDeclarationsWithEsModuleInteropNoCrash.js new file mode 100644 index 00000000000..f35fad8297b --- /dev/null +++ b/tests/baselines/reference/jsxDeclarationsWithEsModuleInteropNoCrash.js @@ -0,0 +1,43 @@ +//// [jsxDeclarationsWithEsModuleInteropNoCrash.jsx] +/// +import PropTypes from 'prop-types'; +import React from 'react'; + +const propTypes = { + bar: PropTypes.bool, +}; + +const defaultProps = { + bar: false, +}; + +function Foo({ bar }) { + return
{bar}
; +} + +Foo.propTypes = propTypes; +Foo.defaultProps = defaultProps; + +export default Foo; + + + +//// [jsxDeclarationsWithEsModuleInteropNoCrash.d.ts] +/// +export default Foo; +declare function Foo({ bar }: { + bar: any; +}): JSX.Element; +declare namespace Foo { + export { propTypes }; + export { defaultProps }; +} +declare namespace propTypes { + import bar = PropTypes.bool; + export { bar }; +} +declare namespace defaultProps { + const bar_1: boolean; + export { bar_1 as bar }; +} +import PropTypes from "prop-types"; diff --git a/tests/baselines/reference/jsxDeclarationsWithEsModuleInteropNoCrash.symbols b/tests/baselines/reference/jsxDeclarationsWithEsModuleInteropNoCrash.symbols new file mode 100644 index 00000000000..1efb61e1258 --- /dev/null +++ b/tests/baselines/reference/jsxDeclarationsWithEsModuleInteropNoCrash.symbols @@ -0,0 +1,52 @@ +=== tests/cases/compiler/jsxDeclarationsWithEsModuleInteropNoCrash.jsx === +/// +import PropTypes from 'prop-types'; +>PropTypes : Symbol(PropTypes, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 1, 6)) + +import React from 'react'; +>React : Symbol(React, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 2, 6)) + +const propTypes = { +>propTypes : Symbol(propTypes, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 4, 5)) + + bar: PropTypes.bool, +>bar : Symbol(bar, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 4, 19)) +>PropTypes.bool : Symbol(PropTypes.bool, Decl(react16.d.ts, 62, 16)) +>PropTypes : Symbol(PropTypes, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 1, 6)) +>bool : Symbol(PropTypes.bool, Decl(react16.d.ts, 62, 16)) + +}; + +const defaultProps = { +>defaultProps : Symbol(defaultProps, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 8, 5)) + + bar: false, +>bar : Symbol(bar, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 8, 22)) + +}; + +function Foo({ bar }) { +>Foo : Symbol(Foo, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 10, 2), Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 14, 1), Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 16, 26)) +>bar : Symbol(bar, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 12, 14)) + + return
{bar}
; +>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) +>bar : Symbol(bar, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 12, 14)) +>div : Symbol(JSX.IntrinsicElements.div, Decl(react16.d.ts, 2420, 114)) +} + +Foo.propTypes = propTypes; +>Foo.propTypes : Symbol(Foo.propTypes, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 14, 1)) +>Foo : Symbol(Foo, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 10, 2), Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 14, 1), Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 16, 26)) +>propTypes : Symbol(Foo.propTypes, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 14, 1)) +>propTypes : Symbol(propTypes, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 4, 5)) + +Foo.defaultProps = defaultProps; +>Foo.defaultProps : Symbol(Foo.defaultProps, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 16, 26)) +>Foo : Symbol(Foo, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 10, 2), Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 14, 1), Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 16, 26)) +>defaultProps : Symbol(Foo.defaultProps, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 16, 26)) +>defaultProps : Symbol(defaultProps, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 8, 5)) + +export default Foo; +>Foo : Symbol(Foo, Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 10, 2), Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 14, 1), Decl(jsxDeclarationsWithEsModuleInteropNoCrash.jsx, 16, 26)) + diff --git a/tests/baselines/reference/jsxDeclarationsWithEsModuleInteropNoCrash.types b/tests/baselines/reference/jsxDeclarationsWithEsModuleInteropNoCrash.types new file mode 100644 index 00000000000..25a02617784 --- /dev/null +++ b/tests/baselines/reference/jsxDeclarationsWithEsModuleInteropNoCrash.types @@ -0,0 +1,58 @@ +=== tests/cases/compiler/jsxDeclarationsWithEsModuleInteropNoCrash.jsx === +/// +import PropTypes from 'prop-types'; +>PropTypes : typeof PropTypes + +import React from 'react'; +>React : typeof React + +const propTypes = { +>propTypes : { bar: PropTypes.Requireable; } +>{ bar: PropTypes.bool,} : { bar: PropTypes.Requireable; } + + bar: PropTypes.bool, +>bar : PropTypes.Requireable +>PropTypes.bool : PropTypes.Requireable +>PropTypes : typeof PropTypes +>bool : PropTypes.Requireable + +}; + +const defaultProps = { +>defaultProps : { bar: boolean; } +>{ bar: false,} : { bar: boolean; } + + bar: false, +>bar : boolean +>false : false + +}; + +function Foo({ bar }) { +>Foo : typeof Foo +>bar : any + + return
{bar}
; +>
{bar}
: JSX.Element +>div : any +>bar : any +>div : any +} + +Foo.propTypes = propTypes; +>Foo.propTypes = propTypes : { bar: PropTypes.Requireable; } +>Foo.propTypes : { bar: PropTypes.Requireable; } +>Foo : typeof Foo +>propTypes : { bar: PropTypes.Requireable; } +>propTypes : { bar: PropTypes.Requireable; } + +Foo.defaultProps = defaultProps; +>Foo.defaultProps = defaultProps : { bar: boolean; } +>Foo.defaultProps : { bar: boolean; } +>Foo : typeof Foo +>defaultProps : { bar: boolean; } +>defaultProps : { bar: boolean; } + +export default Foo; +>Foo : typeof Foo + diff --git a/tests/baselines/reference/lateBoundAssignmentDeclarationSupport2.symbols b/tests/baselines/reference/lateBoundAssignmentDeclarationSupport2.symbols index c4006e93c62..54b247eb108 100644 --- a/tests/baselines/reference/lateBoundAssignmentDeclarationSupport2.symbols +++ b/tests/baselines/reference/lateBoundAssignmentDeclarationSupport2.symbols @@ -26,20 +26,20 @@ const _str = "my-fake-sym"; module.exports[_sym] = "ok"; >module.exports : Symbol("tests/cases/conformance/salsa/lateBoundAssignmentDeclarationSupport2", Decl(lateBoundAssignmentDeclarationSupport2.js, 0, 0)) ->module : Symbol(module, Decl(lateBoundAssignmentDeclarationSupport2.js, 2, 27)) +>module : Symbol(module, Decl(lateBoundAssignmentDeclarationSupport2.js, 5, 28)) >exports : Symbol("tests/cases/conformance/salsa/lateBoundAssignmentDeclarationSupport2", Decl(lateBoundAssignmentDeclarationSupport2.js, 0, 0)) >_sym : Symbol(_sym, Decl(lateBoundAssignmentDeclarationSupport2.js, 1, 5)) module.exports[_str] = "ok"; >module.exports : Symbol("tests/cases/conformance/salsa/lateBoundAssignmentDeclarationSupport2", Decl(lateBoundAssignmentDeclarationSupport2.js, 0, 0)) ->module : Symbol(module, Decl(lateBoundAssignmentDeclarationSupport2.js, 2, 27)) +>module : Symbol(module, Decl(lateBoundAssignmentDeclarationSupport2.js, 5, 28)) >exports : Symbol("tests/cases/conformance/salsa/lateBoundAssignmentDeclarationSupport2", Decl(lateBoundAssignmentDeclarationSupport2.js, 0, 0)) >_str : Symbol(_str, Decl(lateBoundAssignmentDeclarationSupport2.js, 2, 5)) module.exports.S = _sym; >module.exports.S : Symbol(S, Decl(lateBoundAssignmentDeclarationSupport2.js, 5, 28)) >module.exports : Symbol(S, Decl(lateBoundAssignmentDeclarationSupport2.js, 5, 28)) ->module : Symbol(module, Decl(lateBoundAssignmentDeclarationSupport2.js, 2, 27)) +>module : Symbol(module, Decl(lateBoundAssignmentDeclarationSupport2.js, 5, 28)) >exports : Symbol("tests/cases/conformance/salsa/lateBoundAssignmentDeclarationSupport2", Decl(lateBoundAssignmentDeclarationSupport2.js, 0, 0)) >S : Symbol(S, Decl(lateBoundAssignmentDeclarationSupport2.js, 5, 28)) >_sym : Symbol(_sym, Decl(lateBoundAssignmentDeclarationSupport2.js, 1, 5)) diff --git a/tests/baselines/reference/moduleExportsElementAccessAssignment2.symbols b/tests/baselines/reference/moduleExportsElementAccessAssignment2.symbols new file mode 100644 index 00000000000..7fd4c4441f6 --- /dev/null +++ b/tests/baselines/reference/moduleExportsElementAccessAssignment2.symbols @@ -0,0 +1,33 @@ +=== tests/cases/conformance/jsdoc/file1.js === +// this file _should_ be a global file +var GlobalThing = { x: 12 }; +>GlobalThing : Symbol(GlobalThing, Decl(file1.js, 1, 3)) +>x : Symbol(x, Decl(file1.js, 1, 19)) + +/** + * @param {*} type + * @param {*} ctor + * @param {*} exports + */ +function f(type, ctor, exports) { +>f : Symbol(f, Decl(file1.js, 1, 28)) +>type : Symbol(type, Decl(file1.js, 8, 11)) +>ctor : Symbol(ctor, Decl(file1.js, 8, 16)) +>exports : Symbol(exports, Decl(file1.js, 8, 22)) + + if (typeof exports !== "undefined") { +>exports : Symbol(exports, Decl(file1.js, 8, 22)) + + exports["AST_" + type] = ctor; +>exports : Symbol(exports, Decl(file1.js, 8, 22)) +>type : Symbol(type, Decl(file1.js, 8, 11)) +>ctor : Symbol(ctor, Decl(file1.js, 8, 16)) + } +} + +=== tests/cases/conformance/jsdoc/ref.js === +GlobalThing.x +>GlobalThing.x : Symbol(x, Decl(file1.js, 1, 19)) +>GlobalThing : Symbol(GlobalThing, Decl(file1.js, 1, 3)) +>x : Symbol(x, Decl(file1.js, 1, 19)) + diff --git a/tests/baselines/reference/moduleExportsElementAccessAssignment2.types b/tests/baselines/reference/moduleExportsElementAccessAssignment2.types new file mode 100644 index 00000000000..e5e3a4b6e1f --- /dev/null +++ b/tests/baselines/reference/moduleExportsElementAccessAssignment2.types @@ -0,0 +1,42 @@ +=== tests/cases/conformance/jsdoc/file1.js === +// this file _should_ be a global file +var GlobalThing = { x: 12 }; +>GlobalThing : { x: number; } +>{ x: 12 } : { x: number; } +>x : number +>12 : 12 + +/** + * @param {*} type + * @param {*} ctor + * @param {*} exports + */ +function f(type, ctor, exports) { +>f : (type: any, ctor: any, exports: any) => void +>type : any +>ctor : any +>exports : any + + if (typeof exports !== "undefined") { +>typeof exports !== "undefined" : boolean +>typeof exports : "string" | "number" | "bigint" | "boolean" | "symbol" | "undefined" | "object" | "function" +>exports : any +>"undefined" : "undefined" + + exports["AST_" + type] = ctor; +>exports["AST_" + type] = ctor : any +>exports["AST_" + type] : any +>exports : any +>"AST_" + type : string +>"AST_" : "AST_" +>type : any +>ctor : any + } +} + +=== tests/cases/conformance/jsdoc/ref.js === +GlobalThing.x +>GlobalThing.x : number +>GlobalThing : { x: number; } +>x : number + diff --git a/tests/baselines/reference/noEmitAndComposite.errors.txt b/tests/baselines/reference/noEmitAndComposite.errors.txt deleted file mode 100644 index fe6de6ae441..00000000000 --- a/tests/baselines/reference/noEmitAndComposite.errors.txt +++ /dev/null @@ -1,19 +0,0 @@ -/tsconfig.json(3,9): error TS5053: Option 'noEmit' cannot be specified with option 'composite'. -/tsconfig.json(4,9): error TS5053: Option 'noEmit' cannot be specified with option 'composite'. - - -==== /tsconfig.json (2 errors) ==== - { - "compilerOptions": { - "noEmit": true, - ~~~~~~~~ -!!! error TS5053: Option 'noEmit' cannot be specified with option 'composite'. - "composite": true - ~~~~~~~~~~~ -!!! error TS5053: Option 'noEmit' cannot be specified with option 'composite'. - } - } - -==== /a.ts (0 errors) ==== - const x = 10; - \ No newline at end of file diff --git a/tests/baselines/reference/noEmitAndComposite.symbols b/tests/baselines/reference/noEmitAndComposite.symbols deleted file mode 100644 index 05c35bcf58a..00000000000 --- a/tests/baselines/reference/noEmitAndComposite.symbols +++ /dev/null @@ -1,4 +0,0 @@ -=== /a.ts === -const x = 10; ->x : Symbol(x, Decl(a.ts, 0, 5)) - diff --git a/tests/baselines/reference/noEmitAndComposite.types b/tests/baselines/reference/noEmitAndComposite.types deleted file mode 100644 index ed892fed2ba..00000000000 --- a/tests/baselines/reference/noEmitAndComposite.types +++ /dev/null @@ -1,5 +0,0 @@ -=== /a.ts === -const x = 10; ->x : 10 ->10 : 10 - diff --git a/tests/baselines/reference/noEmitAndIncremental.errors.txt b/tests/baselines/reference/noEmitAndIncremental.errors.txt deleted file mode 100644 index c257e9ba540..00000000000 --- a/tests/baselines/reference/noEmitAndIncremental.errors.txt +++ /dev/null @@ -1,20 +0,0 @@ -/tsconfig.json(3,9): error TS5053: Option 'noEmit' cannot be specified with option 'incremental'. -/tsconfig.json(4,9): error TS5053: Option 'noEmit' cannot be specified with option 'incremental'. - - -==== /tsconfig.json (2 errors) ==== - { - "compilerOptions": { - "noEmit": true, - ~~~~~~~~ -!!! error TS5053: Option 'noEmit' cannot be specified with option 'incremental'. - "incremental": true - ~~~~~~~~~~~~~ -!!! error TS5053: Option 'noEmit' cannot be specified with option 'incremental'. - } - } - - -==== /a.ts (0 errors) ==== - const x = 10; - \ No newline at end of file diff --git a/tests/baselines/reference/noEmitAndIncremental.symbols b/tests/baselines/reference/noEmitAndIncremental.symbols deleted file mode 100644 index 05c35bcf58a..00000000000 --- a/tests/baselines/reference/noEmitAndIncremental.symbols +++ /dev/null @@ -1,4 +0,0 @@ -=== /a.ts === -const x = 10; ->x : Symbol(x, Decl(a.ts, 0, 5)) - diff --git a/tests/baselines/reference/noEmitAndIncremental.types b/tests/baselines/reference/noEmitAndIncremental.types deleted file mode 100644 index ed892fed2ba..00000000000 --- a/tests/baselines/reference/noEmitAndIncremental.types +++ /dev/null @@ -1,5 +0,0 @@ -=== /a.ts === -const x = 10; ->x : 10 ->10 : 10 - diff --git a/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.js b/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.js index 5392b163477..633a1d07876 100644 --- a/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.js +++ b/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.js @@ -5,6 +5,8 @@ declare class Something { private static someStaticVar; private someVar; + private get getter(); + private set setter(v); } //// [app.ts] diff --git a/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.symbols b/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.symbols index 0cfd1cbff07..9908d70ba5e 100644 --- a/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.symbols +++ b/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.symbols @@ -13,5 +13,12 @@ declare class Something private someVar; >someVar : Symbol(Something.someVar, Decl(test.d.ts, 2, 33)) + + private get getter(); +>getter : Symbol(Something.getter, Decl(test.d.ts, 3, 20)) + + private set setter(v); +>setter : Symbol(Something.setter, Decl(test.d.ts, 4, 25)) +>v : Symbol(v, Decl(test.d.ts, 5, 23)) } diff --git a/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.types b/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.types index 071d8a1aa88..5f69adcf631 100644 --- a/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.types +++ b/tests/baselines/reference/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.types @@ -14,5 +14,12 @@ declare class Something private someVar; >someVar : any + + private get getter(); +>getter : any + + private set setter(v); +>setter : any +>v : any } diff --git a/tests/baselines/reference/nullishCoalescingOperator12.js b/tests/baselines/reference/nullishCoalescingOperator12.js new file mode 100644 index 00000000000..f648af8e0b7 --- /dev/null +++ b/tests/baselines/reference/nullishCoalescingOperator12.js @@ -0,0 +1,10 @@ +//// [nullishCoalescingOperator12.ts] +const obj: { arr: any[] } = { arr: [] }; +for (const i of obj?.arr ?? []) { } + + +//// [nullishCoalescingOperator12.js] +"use strict"; +var _a, _b; +const obj = { arr: [] }; +for (const i of (_b = (_a = obj) === null || _a === void 0 ? void 0 : _a.arr, (_b !== null && _b !== void 0 ? _b : []))) { } diff --git a/tests/baselines/reference/nullishCoalescingOperator12.symbols b/tests/baselines/reference/nullishCoalescingOperator12.symbols new file mode 100644 index 00000000000..6be9ed5c5e4 --- /dev/null +++ b/tests/baselines/reference/nullishCoalescingOperator12.symbols @@ -0,0 +1,12 @@ +=== tests/cases/conformance/expressions/nullishCoalescingOperator/nullishCoalescingOperator12.ts === +const obj: { arr: any[] } = { arr: [] }; +>obj : Symbol(obj, Decl(nullishCoalescingOperator12.ts, 0, 5)) +>arr : Symbol(arr, Decl(nullishCoalescingOperator12.ts, 0, 12)) +>arr : Symbol(arr, Decl(nullishCoalescingOperator12.ts, 0, 29)) + +for (const i of obj?.arr ?? []) { } +>i : Symbol(i, Decl(nullishCoalescingOperator12.ts, 1, 10)) +>obj?.arr : Symbol(arr, Decl(nullishCoalescingOperator12.ts, 0, 12)) +>obj : Symbol(obj, Decl(nullishCoalescingOperator12.ts, 0, 5)) +>arr : Symbol(arr, Decl(nullishCoalescingOperator12.ts, 0, 12)) + diff --git a/tests/baselines/reference/nullishCoalescingOperator12.types b/tests/baselines/reference/nullishCoalescingOperator12.types new file mode 100644 index 00000000000..d0b52b7afbf --- /dev/null +++ b/tests/baselines/reference/nullishCoalescingOperator12.types @@ -0,0 +1,16 @@ +=== tests/cases/conformance/expressions/nullishCoalescingOperator/nullishCoalescingOperator12.ts === +const obj: { arr: any[] } = { arr: [] }; +>obj : { arr: any[]; } +>arr : any[] +>{ arr: [] } : { arr: never[]; } +>arr : never[] +>[] : never[] + +for (const i of obj?.arr ?? []) { } +>i : any +>obj?.arr ?? [] : any[] +>obj?.arr : any[] +>obj : { arr: any[]; } +>arr : any[] +>[] : never[] + diff --git a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers02.errors.txt b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers02.errors.txt index 5809148707b..3590b42e374 100644 --- a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers02.errors.txt +++ b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers02.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/es6/destructuring/objectBindingPatternKeywordIdentifiers02.ts(1,14): error TS1003: Identifier expected. +tests/cases/conformance/es6/destructuring/objectBindingPatternKeywordIdentifiers02.ts(1,14): error TS1359: Identifier expected. 'while' is a reserved word that cannot be used here. tests/cases/conformance/es6/destructuring/objectBindingPatternKeywordIdentifiers02.ts(1,20): error TS1005: ':' expected. ==== tests/cases/conformance/es6/destructuring/objectBindingPatternKeywordIdentifiers02.ts (2 errors) ==== var { while: while } = { while: 1 } ~~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'while' is a reserved word that cannot be used here. ~ !!! error TS1005: ':' expected. \ No newline at end of file diff --git a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers04.errors.txt b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers04.errors.txt index 5481b5efe55..ed8f14e1fd0 100644 --- a/tests/baselines/reference/objectBindingPatternKeywordIdentifiers04.errors.txt +++ b/tests/baselines/reference/objectBindingPatternKeywordIdentifiers04.errors.txt @@ -1,10 +1,10 @@ -tests/cases/conformance/es6/destructuring/objectBindingPatternKeywordIdentifiers04.ts(1,16): error TS1003: Identifier expected. +tests/cases/conformance/es6/destructuring/objectBindingPatternKeywordIdentifiers04.ts(1,16): error TS1359: Identifier expected. 'while' is a reserved word that cannot be used here. tests/cases/conformance/es6/destructuring/objectBindingPatternKeywordIdentifiers04.ts(1,22): error TS1005: ':' expected. ==== tests/cases/conformance/es6/destructuring/objectBindingPatternKeywordIdentifiers04.ts (2 errors) ==== var { "while": while } = { while: 1 } ~~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'while' is a reserved word that cannot be used here. ~ !!! error TS1005: ':' expected. \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolIndexer1.errors.txt b/tests/baselines/reference/parserES5SymbolIndexer1.errors.txt index adfac8f700f..a0010dc0a27 100644 --- a/tests/baselines/reference/parserES5SymbolIndexer1.errors.txt +++ b/tests/baselines/reference/parserES5SymbolIndexer1.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolIndexer1.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolIndexer1.ts(2,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolIndexer1.ts (1 errors) ==== interface I { [s: symbol]: string; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolIndexer2.errors.txt b/tests/baselines/reference/parserES5SymbolIndexer2.errors.txt index 12eef8ec049..acc43ed9b74 100644 --- a/tests/baselines/reference/parserES5SymbolIndexer2.errors.txt +++ b/tests/baselines/reference/parserES5SymbolIndexer2.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolIndexer2.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolIndexer2.ts(2,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolIndexer2.ts (1 errors) ==== class C { [s: symbol]: string; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserES5SymbolIndexer3.errors.txt b/tests/baselines/reference/parserES5SymbolIndexer3.errors.txt index c9cd9db4fab..12d8819c601 100644 --- a/tests/baselines/reference/parserES5SymbolIndexer3.errors.txt +++ b/tests/baselines/reference/parserES5SymbolIndexer3.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolIndexer3.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolIndexer3.ts(2,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/parser/ecmascript5/Symbols/parserES5SymbolIndexer3.ts (1 errors) ==== var x: { [s: symbol]: string; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserEnumDeclaration4.errors.txt b/tests/baselines/reference/parserEnumDeclaration4.errors.txt index a91aa5cab16..2a90824df9e 100644 --- a/tests/baselines/reference/parserEnumDeclaration4.errors.txt +++ b/tests/baselines/reference/parserEnumDeclaration4.errors.txt @@ -1,8 +1,8 @@ -tests/cases/conformance/parser/ecmascript5/EnumDeclarations/parserEnumDeclaration4.ts(1,6): error TS1003: Identifier expected. +tests/cases/conformance/parser/ecmascript5/EnumDeclarations/parserEnumDeclaration4.ts(1,6): error TS1359: Identifier expected. 'void' is a reserved word that cannot be used here. ==== tests/cases/conformance/parser/ecmascript5/EnumDeclarations/parserEnumDeclaration4.ts (1 errors) ==== enum void { ~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'void' is a reserved word that cannot be used here. } \ No newline at end of file diff --git a/tests/baselines/reference/parserIndexSignature6.errors.txt b/tests/baselines/reference/parserIndexSignature6.errors.txt index db53f219832..9df13e05b6c 100644 --- a/tests/baselines/reference/parserIndexSignature6.errors.txt +++ b/tests/baselines/reference/parserIndexSignature6.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript5/IndexSignatures/parserIndexSignature6.ts(2,4): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/parser/ecmascript5/IndexSignatures/parserIndexSignature6.ts(2,4): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/parser/ecmascript5/IndexSignatures/parserIndexSignature6.ts (1 errors) ==== interface I { [a:boolean] ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserIndexSignature8.errors.txt b/tests/baselines/reference/parserIndexSignature8.errors.txt index 87369df1b76..5ca6f11573f 100644 --- a/tests/baselines/reference/parserIndexSignature8.errors.txt +++ b/tests/baselines/reference/parserIndexSignature8.errors.txt @@ -1,12 +1,12 @@ -tests/cases/conformance/parser/ecmascript5/IndexSignatures/parserIndexSignature8.ts(1,13): error TS1023: An index signature parameter type must be 'string' or 'number'. -tests/cases/conformance/parser/ecmascript5/IndexSignatures/parserIndexSignature8.ts(2,14): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/parser/ecmascript5/IndexSignatures/parserIndexSignature8.ts(1,13): error TS1023: An index signature parameter type must be either 'string' or 'number'. +tests/cases/conformance/parser/ecmascript5/IndexSignatures/parserIndexSignature8.ts(2,14): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/parser/ecmascript5/IndexSignatures/parserIndexSignature8.ts (2 errors) ==== var foo: { [index: any]; }; // expect an error here ~~~~~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. var foo2: { [index: RegExp]; }; // expect an error here ~~~~~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. \ No newline at end of file diff --git a/tests/baselines/reference/parserSymbolIndexer1.errors.txt b/tests/baselines/reference/parserSymbolIndexer1.errors.txt index 5c6c38d52b1..b9a34890151 100644 --- a/tests/baselines/reference/parserSymbolIndexer1.errors.txt +++ b/tests/baselines/reference/parserSymbolIndexer1.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer1.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer1.ts(2,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer1.ts (1 errors) ==== interface I { [s: symbol]: string; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserSymbolIndexer2.errors.txt b/tests/baselines/reference/parserSymbolIndexer2.errors.txt index 3961f4942de..3b8735feef9 100644 --- a/tests/baselines/reference/parserSymbolIndexer2.errors.txt +++ b/tests/baselines/reference/parserSymbolIndexer2.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer2.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer2.ts(2,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer2.ts (1 errors) ==== class C { [s: symbol]: string; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/parserSymbolIndexer4.errors.txt b/tests/baselines/reference/parserSymbolIndexer4.errors.txt index 1cf184a4847..4da102891a0 100644 --- a/tests/baselines/reference/parserSymbolIndexer4.errors.txt +++ b/tests/baselines/reference/parserSymbolIndexer4.errors.txt @@ -1,9 +1,9 @@ -tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer4.ts(2,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer4.ts(2,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/parser/ecmascript6/Symbols/parserSymbolIndexer4.ts (1 errors) ==== var x: { [s: symbol]: string; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution7_classic.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution7_classic.trace.json index 78a273ae059..9ee972c70ee 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution7_classic.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution7_classic.trace.json @@ -12,7 +12,7 @@ "======== Module name './project/file2' was successfully resolved to 'c:/root/generated/src/project/file2.ts'. ========", "======== Resolving module 'module3' from 'c:/root/src/file1.ts'. ========", "Module resolution kind is not specified, using 'Classic'.", - "'baseUrl' option is set to 'c:/root/', using this value to resolve non-relative module name 'module3'.", + "'baseUrl' option is set to 'c:/root', using this value to resolve non-relative module name 'module3'.", "'paths' option is specified, looking for a pattern to match module name 'module3'.", "Module name 'module3', matched pattern '*'.", "Trying substitution '*', candidate module location: 'module3'.", @@ -35,7 +35,7 @@ "======== Module name 'module3' was successfully resolved to 'c:/module3.d.ts'. ========", "======== Resolving module 'module1' from 'c:/root/generated/src/project/file2.ts'. ========", "Module resolution kind is not specified, using 'Classic'.", - "'baseUrl' option is set to 'c:/root/', using this value to resolve non-relative module name 'module1'.", + "'baseUrl' option is set to 'c:/root', using this value to resolve non-relative module name 'module1'.", "'paths' option is specified, looking for a pattern to match module name 'module1'.", "Module name 'module1', matched pattern '*'.", "Trying substitution '*', candidate module location: 'module1'.", @@ -49,7 +49,7 @@ "======== Module name 'module1' was successfully resolved to 'c:/shared/module1.d.ts'. ========", "======== Resolving module 'templates/module2' from 'c:/root/generated/src/project/file2.ts'. ========", "Module resolution kind is not specified, using 'Classic'.", - "'baseUrl' option is set to 'c:/root/', using this value to resolve non-relative module name 'templates/module2'.", + "'baseUrl' option is set to 'c:/root', using this value to resolve non-relative module name 'templates/module2'.", "'paths' option is specified, looking for a pattern to match module name 'templates/module2'.", "Module name 'templates/module2', matched pattern 'templates/*'.", "Trying substitution 'generated/src/templates/*', candidate module location: 'generated/src/templates/module2'.", diff --git a/tests/baselines/reference/pathMappingBasedModuleResolution7_node.trace.json b/tests/baselines/reference/pathMappingBasedModuleResolution7_node.trace.json index 50e4a6fabeb..dd78aa4d449 100644 --- a/tests/baselines/reference/pathMappingBasedModuleResolution7_node.trace.json +++ b/tests/baselines/reference/pathMappingBasedModuleResolution7_node.trace.json @@ -15,7 +15,7 @@ "======== Module name './project/file2' was successfully resolved to 'c:/root/generated/src/project/file2.ts'. ========", "======== Resolving module 'module3' from 'c:/root/src/file1.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", - "'baseUrl' option is set to 'c:/root/', using this value to resolve non-relative module name 'module3'.", + "'baseUrl' option is set to 'c:/root', using this value to resolve non-relative module name 'module3'.", "'paths' option is specified, looking for a pattern to match module name 'module3'.", "Module name 'module3', matched pattern '*'.", "Trying substitution '*', candidate module location: 'module3'.", @@ -40,7 +40,7 @@ "======== Module name 'module3' was successfully resolved to 'c:/node_modules/module3.d.ts'. ========", "======== Resolving module 'module1' from 'c:/root/generated/src/project/file2.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", - "'baseUrl' option is set to 'c:/root/', using this value to resolve non-relative module name 'module1'.", + "'baseUrl' option is set to 'c:/root', using this value to resolve non-relative module name 'module1'.", "'paths' option is specified, looking for a pattern to match module name 'module1'.", "Module name 'module1', matched pattern '*'.", "Trying substitution '*', candidate module location: 'module1'.", @@ -61,7 +61,7 @@ "======== Module name 'module1' was successfully resolved to 'c:/shared/module1/index.d.ts'. ========", "======== Resolving module 'templates/module2' from 'c:/root/generated/src/project/file2.ts'. ========", "Module resolution kind is not specified, using 'NodeJs'.", - "'baseUrl' option is set to 'c:/root/', using this value to resolve non-relative module name 'templates/module2'.", + "'baseUrl' option is set to 'c:/root', using this value to resolve non-relative module name 'templates/module2'.", "'paths' option is specified, looking for a pattern to match module name 'templates/module2'.", "Module name 'templates/module2', matched pattern 'templates/*'.", "Trying substitution 'generated/src/templates/*', candidate module location: 'generated/src/templates/module2'.", diff --git a/tests/baselines/reference/propertyAccessChain.js b/tests/baselines/reference/propertyAccessChain.js index 0c15856b15c..47f4aa1c334 100644 --- a/tests/baselines/reference/propertyAccessChain.js +++ b/tests/baselines/reference/propertyAccessChain.js @@ -13,13 +13,22 @@ o4.b?.c.d?.e; declare const o5: { b?(): { c: { d?: { e: string } } } }; o5.b?.().c.d?.e; - + +// GH#33744 +declare const o6: () => undefined | ({ x: number }); +o6()?.x; + +// GH#34109 +o1?.b ? 1 : 0; //// [propertyAccessChain.js] "use strict"; -var _a, _b, _c, _d, _e, _f, _g, _h; +var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; (_a = o1) === null || _a === void 0 ? void 0 : _a.b; (_b = o2) === null || _b === void 0 ? void 0 : _b.b.c; (_c = o3.b) === null || _c === void 0 ? void 0 : _c.c; (_e = (_d = o4.b) === null || _d === void 0 ? void 0 : _d.c.d) === null || _e === void 0 ? void 0 : _e.e; (_h = (_g = (_f = o5).b) === null || _g === void 0 ? void 0 : _g.call(_f).c.d) === null || _h === void 0 ? void 0 : _h.e; +(_j = o6()) === null || _j === void 0 ? void 0 : _j.x; +// GH#34109 +((_k = o1) === null || _k === void 0 ? void 0 : _k.b) ? 1 : 0; diff --git a/tests/baselines/reference/propertyAccessChain.symbols b/tests/baselines/reference/propertyAccessChain.symbols index 8b5cea9fe67..21f694a57f9 100644 --- a/tests/baselines/reference/propertyAccessChain.symbols +++ b/tests/baselines/reference/propertyAccessChain.symbols @@ -68,3 +68,20 @@ o5.b?.().c.d?.e; >d : Symbol(d, Decl(propertyAccessChain.ts, 12, 32)) >e : Symbol(e, Decl(propertyAccessChain.ts, 12, 38)) +// GH#33744 +declare const o6: () => undefined | ({ x: number }); +>o6 : Symbol(o6, Decl(propertyAccessChain.ts, 16, 13)) +>T : Symbol(T, Decl(propertyAccessChain.ts, 16, 19)) +>x : Symbol(x, Decl(propertyAccessChain.ts, 16, 41)) + +o6()?.x; +>o6()?.x : Symbol(x, Decl(propertyAccessChain.ts, 16, 41)) +>o6 : Symbol(o6, Decl(propertyAccessChain.ts, 16, 13)) +>x : Symbol(x, Decl(propertyAccessChain.ts, 16, 41)) + +// GH#34109 +o1?.b ? 1 : 0; +>o1?.b : Symbol(b, Decl(propertyAccessChain.ts, 0, 31)) +>o1 : Symbol(o1, Decl(propertyAccessChain.ts, 0, 13)) +>b : Symbol(b, Decl(propertyAccessChain.ts, 0, 31)) + diff --git a/tests/baselines/reference/propertyAccessChain.types b/tests/baselines/reference/propertyAccessChain.types index 2cb030ac3f6..60428ac5c1e 100644 --- a/tests/baselines/reference/propertyAccessChain.types +++ b/tests/baselines/reference/propertyAccessChain.types @@ -69,3 +69,23 @@ o5.b?.().c.d?.e; >d : { e: string; } | undefined >e : string | undefined +// GH#33744 +declare const o6: () => undefined | ({ x: number }); +>o6 : () => { x: number; } | undefined +>x : number + +o6()?.x; +>o6()?.x : number | undefined +>o6() : { x: number; } | undefined +>o6 : () => { x: number; } | undefined +>x : number | undefined + +// GH#34109 +o1?.b ? 1 : 0; +>o1?.b ? 1 : 0 : 0 | 1 +>o1?.b : string | undefined +>o1 : { b: string; } | undefined +>b : string | undefined +>1 : 1 +>0 : 0 + diff --git a/tests/baselines/reference/propertyOverridesMethod.errors.txt b/tests/baselines/reference/propertyOverridesMethod.errors.txt deleted file mode 100644 index aaee2d48cf6..00000000000 --- a/tests/baselines/reference/propertyOverridesMethod.errors.txt +++ /dev/null @@ -1,13 +0,0 @@ -tests/cases/conformance/classes/propertyMemberDeclarations/propertyOverridesMethod.ts(5,5): error TS2424: Class 'A' defines instance member function 'm', but extended class 'B' defines it as instance member property. - - -==== tests/cases/conformance/classes/propertyMemberDeclarations/propertyOverridesMethod.ts (1 errors) ==== - class A { - m() { } - } - class B extends A { - m = () => 1 - ~ -!!! error TS2424: Class 'A' defines instance member function 'm', but extended class 'B' defines it as instance member property. - } - \ No newline at end of file diff --git a/tests/baselines/reference/propertyOverridingPrototype.errors.txt b/tests/baselines/reference/propertyOverridingPrototype.errors.txt deleted file mode 100644 index a585f7999f6..00000000000 --- a/tests/baselines/reference/propertyOverridingPrototype.errors.txt +++ /dev/null @@ -1,16 +0,0 @@ -tests/cases/compiler/propertyOverridingPrototype.ts(7,5): error TS2424: Class 'Base' defines instance member function 'foo', but extended class 'Derived' defines it as instance member property. - - -==== tests/cases/compiler/propertyOverridingPrototype.ts (1 errors) ==== - class Base { - foo() { - } - } - - class Derived extends Base { - foo: () => { }; - ~~~ -!!! error TS2424: Class 'Base' defines instance member function 'foo', but extended class 'Derived' defines it as instance member property. - } - - \ No newline at end of file diff --git a/tests/baselines/reference/reachabilityChecks4.errors.txt b/tests/baselines/reference/reachabilityChecks4.errors.txt index fdbb9d23ee8..4c20700f9dd 100644 --- a/tests/baselines/reference/reachabilityChecks4.errors.txt +++ b/tests/baselines/reference/reachabilityChecks4.errors.txt @@ -1,14 +1,15 @@ tests/cases/compiler/reachabilityChecks4.ts(6,9): error TS7029: Fallthrough case in switch. +tests/cases/compiler/reachabilityChecks4.ts(22,9): error TS7029: Fallthrough case in switch. -==== tests/cases/compiler/reachabilityChecks4.ts (1 errors) ==== +==== tests/cases/compiler/reachabilityChecks4.ts (2 errors) ==== function foo(x, y) { switch (x) { case 1: case 2: return 1; case 3: - ~~~~ + ~~~~~~~ !!! error TS7029: Fallthrough case in switch. if (y) { return 2; @@ -16,4 +17,58 @@ tests/cases/compiler/reachabilityChecks4.ts(6,9): error TS7029: Fallthrough case case 4: return 3; } - } \ No newline at end of file + } + + declare function noop(): void; + declare function fail(): never; + + function f1(x: 0 | 1 | 2) { + switch (x) { + case 0: + fail(); + case 1: + ~~~~~~~ +!!! error TS7029: Fallthrough case in switch. + noop(); + case 2: + return; + } + } + + // Repro from #34021 + + type Behavior = 'SLIDE' | 'SLIDE_OUT' + type Direction = 'LEFT' | 'RIGHT' | 'TOP' | 'BOTTOM' + + interface Transition { + behavior: Behavior + direction: Direction + } + + function f2(transition: Transition): any { + switch (transition.behavior) { + case 'SLIDE': + switch (transition.direction) { + case 'LEFT': + return [] + case 'RIGHT': + return [] + case 'TOP': + return [] + case 'BOTTOM': + return [] + } + case 'SLIDE_OUT': + switch (transition.direction) { + case 'LEFT': + return [] + case 'RIGHT': + return [] + case 'TOP': + return [] + case 'BOTTOM': + return [] + } + } + } + \ No newline at end of file diff --git a/tests/baselines/reference/reachabilityChecks4.js b/tests/baselines/reference/reachabilityChecks4.js index de84c445cff..57175867532 100644 --- a/tests/baselines/reference/reachabilityChecks4.js +++ b/tests/baselines/reference/reachabilityChecks4.js @@ -11,7 +11,59 @@ function foo(x, y) { case 4: return 3; } -} +} + +declare function noop(): void; +declare function fail(): never; + +function f1(x: 0 | 1 | 2) { + switch (x) { + case 0: + fail(); + case 1: + noop(); + case 2: + return; + } +} + +// Repro from #34021 + +type Behavior = 'SLIDE' | 'SLIDE_OUT' +type Direction = 'LEFT' | 'RIGHT' | 'TOP' | 'BOTTOM' + +interface Transition { + behavior: Behavior + direction: Direction +} + +function f2(transition: Transition): any { + switch (transition.behavior) { + case 'SLIDE': + switch (transition.direction) { + case 'LEFT': + return [] + case 'RIGHT': + return [] + case 'TOP': + return [] + case 'BOTTOM': + return [] + } + case 'SLIDE_OUT': + switch (transition.direction) { + case 'LEFT': + return [] + case 'RIGHT': + return [] + case 'TOP': + return [] + case 'BOTTOM': + return [] + } + } +} + //// [reachabilityChecks4.js] function foo(x, y) { @@ -27,3 +79,39 @@ function foo(x, y) { return 3; } } +function f1(x) { + switch (x) { + case 0: + fail(); + case 1: + noop(); + case 2: + return; + } +} +function f2(transition) { + switch (transition.behavior) { + case 'SLIDE': + switch (transition.direction) { + case 'LEFT': + return []; + case 'RIGHT': + return []; + case 'TOP': + return []; + case 'BOTTOM': + return []; + } + case 'SLIDE_OUT': + switch (transition.direction) { + case 'LEFT': + return []; + case 'RIGHT': + return []; + case 'TOP': + return []; + case 'BOTTOM': + return []; + } + } +} diff --git a/tests/baselines/reference/reachabilityChecks4.symbols b/tests/baselines/reference/reachabilityChecks4.symbols index 76800cbcd86..6f68f15fda8 100644 --- a/tests/baselines/reference/reachabilityChecks4.symbols +++ b/tests/baselines/reference/reachabilityChecks4.symbols @@ -20,3 +20,93 @@ function foo(x, y) { return 3; } } + +declare function noop(): void; +>noop : Symbol(noop, Decl(reachabilityChecks4.ts, 12, 1)) + +declare function fail(): never; +>fail : Symbol(fail, Decl(reachabilityChecks4.ts, 14, 30)) + +function f1(x: 0 | 1 | 2) { +>f1 : Symbol(f1, Decl(reachabilityChecks4.ts, 15, 31)) +>x : Symbol(x, Decl(reachabilityChecks4.ts, 17, 12)) + + switch (x) { +>x : Symbol(x, Decl(reachabilityChecks4.ts, 17, 12)) + + case 0: + fail(); +>fail : Symbol(fail, Decl(reachabilityChecks4.ts, 14, 30)) + + case 1: + noop(); +>noop : Symbol(noop, Decl(reachabilityChecks4.ts, 12, 1)) + + case 2: + return; + } +} + +// Repro from #34021 + +type Behavior = 'SLIDE' | 'SLIDE_OUT' +>Behavior : Symbol(Behavior, Decl(reachabilityChecks4.ts, 26, 1)) + +type Direction = 'LEFT' | 'RIGHT' | 'TOP' | 'BOTTOM' +>Direction : Symbol(Direction, Decl(reachabilityChecks4.ts, 30, 37)) + +interface Transition { +>Transition : Symbol(Transition, Decl(reachabilityChecks4.ts, 31, 52)) + + behavior: Behavior +>behavior : Symbol(Transition.behavior, Decl(reachabilityChecks4.ts, 33, 22)) +>Behavior : Symbol(Behavior, Decl(reachabilityChecks4.ts, 26, 1)) + + direction: Direction +>direction : Symbol(Transition.direction, Decl(reachabilityChecks4.ts, 34, 20)) +>Direction : Symbol(Direction, Decl(reachabilityChecks4.ts, 30, 37)) +} + +function f2(transition: Transition): any { +>f2 : Symbol(f2, Decl(reachabilityChecks4.ts, 36, 1)) +>transition : Symbol(transition, Decl(reachabilityChecks4.ts, 38, 12)) +>Transition : Symbol(Transition, Decl(reachabilityChecks4.ts, 31, 52)) + + switch (transition.behavior) { +>transition.behavior : Symbol(Transition.behavior, Decl(reachabilityChecks4.ts, 33, 22)) +>transition : Symbol(transition, Decl(reachabilityChecks4.ts, 38, 12)) +>behavior : Symbol(Transition.behavior, Decl(reachabilityChecks4.ts, 33, 22)) + + case 'SLIDE': + switch (transition.direction) { +>transition.direction : Symbol(Transition.direction, Decl(reachabilityChecks4.ts, 34, 20)) +>transition : Symbol(transition, Decl(reachabilityChecks4.ts, 38, 12)) +>direction : Symbol(Transition.direction, Decl(reachabilityChecks4.ts, 34, 20)) + + case 'LEFT': + return [] + case 'RIGHT': + return [] + case 'TOP': + return [] + case 'BOTTOM': + return [] + } + case 'SLIDE_OUT': + switch (transition.direction) { +>transition.direction : Symbol(Transition.direction, Decl(reachabilityChecks4.ts, 34, 20)) +>transition : Symbol(transition, Decl(reachabilityChecks4.ts, 38, 12)) +>direction : Symbol(Transition.direction, Decl(reachabilityChecks4.ts, 34, 20)) + + case 'LEFT': + return [] + case 'RIGHT': + return [] + case 'TOP': + return [] + case 'BOTTOM': + return [] + } + } +} + diff --git a/tests/baselines/reference/reachabilityChecks4.types b/tests/baselines/reference/reachabilityChecks4.types index dbe834fb10a..27051b3550d 100644 --- a/tests/baselines/reference/reachabilityChecks4.types +++ b/tests/baselines/reference/reachabilityChecks4.types @@ -32,3 +32,130 @@ function foo(x, y) { >3 : 3 } } + +declare function noop(): void; +>noop : () => void + +declare function fail(): never; +>fail : () => never + +function f1(x: 0 | 1 | 2) { +>f1 : (x: 0 | 1 | 2) => void +>x : 0 | 1 | 2 + + switch (x) { +>x : 0 | 1 | 2 + + case 0: +>0 : 0 + + fail(); +>fail() : never +>fail : () => never + + case 1: +>1 : 1 + + noop(); +>noop() : void +>noop : () => void + + case 2: +>2 : 2 + + return; + } +} + +// Repro from #34021 + +type Behavior = 'SLIDE' | 'SLIDE_OUT' +>Behavior : Behavior + +type Direction = 'LEFT' | 'RIGHT' | 'TOP' | 'BOTTOM' +>Direction : Direction + +interface Transition { + behavior: Behavior +>behavior : Behavior + + direction: Direction +>direction : Direction +} + +function f2(transition: Transition): any { +>f2 : (transition: Transition) => any +>transition : Transition + + switch (transition.behavior) { +>transition.behavior : Behavior +>transition : Transition +>behavior : Behavior + + case 'SLIDE': +>'SLIDE' : "SLIDE" + + switch (transition.direction) { +>transition.direction : Direction +>transition : Transition +>direction : Direction + + case 'LEFT': +>'LEFT' : "LEFT" + + return [] +>[] : undefined[] + + case 'RIGHT': +>'RIGHT' : "RIGHT" + + return [] +>[] : undefined[] + + case 'TOP': +>'TOP' : "TOP" + + return [] +>[] : undefined[] + + case 'BOTTOM': +>'BOTTOM' : "BOTTOM" + + return [] +>[] : undefined[] + } + case 'SLIDE_OUT': +>'SLIDE_OUT' : "SLIDE_OUT" + + switch (transition.direction) { +>transition.direction : Direction +>transition : Transition +>direction : Direction + + case 'LEFT': +>'LEFT' : "LEFT" + + return [] +>[] : undefined[] + + case 'RIGHT': +>'RIGHT' : "RIGHT" + + return [] +>[] : undefined[] + + case 'TOP': +>'TOP' : "TOP" + + return [] +>[] : undefined[] + + case 'BOTTOM': +>'BOTTOM' : "BOTTOM" + + return [] +>[] : undefined[] + } + } +} + diff --git a/tests/baselines/reference/readonlyArraysAndTuples.types b/tests/baselines/reference/readonlyArraysAndTuples.types index a0db326f35e..1f443c702f0 100644 --- a/tests/baselines/reference/readonlyArraysAndTuples.types +++ b/tests/baselines/reference/readonlyArraysAndTuples.types @@ -6,7 +6,7 @@ type T11 = Array; >T11 : T11 type T12 = readonly string[]; ->T12 : readonly string[] +>T12 : T12 type T13 = ReadonlyArray; >T13 : T13 @@ -15,7 +15,7 @@ type T20 = [number, number]; >T20 : T20 type T21 = readonly [number, number]; ->T21 : readonly [number, number] +>T21 : T21 type T30 = readonly string; // Error >T30 : string @@ -24,10 +24,10 @@ type T31 = readonly T; // Error >T31 : T type T32 = readonly readonly string[]; // Error ->T32 : readonly string[] +>T32 : T32 type T33 = readonly Array; // Error ->T33 : string[] +>T33 : T33 function f1(ma: string[], ra: readonly string[], mt: [string, string], rt: readonly [string, string]) { >f1 : (ma: string[], ra: readonly string[], mt: [string, string], rt: readonly [string, string]) => void diff --git a/tests/baselines/reference/readonlyArraysAndTuples2.types b/tests/baselines/reference/readonlyArraysAndTuples2.types index be75e046528..21872ad63d2 100644 --- a/tests/baselines/reference/readonlyArraysAndTuples2.types +++ b/tests/baselines/reference/readonlyArraysAndTuples2.types @@ -6,7 +6,7 @@ type T11 = Array; >T11 : T11 type T12 = readonly string[]; ->T12 : readonly string[] +>T12 : T12 type T13 = ReadonlyArray; >T13 : T13 @@ -15,7 +15,7 @@ type T20 = [number, number]; >T20 : T20 type T21 = readonly [number, number]; ->T21 : readonly [number, number] +>T21 : T21 declare function f1(ma: string[], ra: readonly string[], mt: [string, string], rt: readonly [string, string]): readonly [string, string]; >f1 : (ma: string[], ra: readonly string[], mt: [string, string], rt: readonly [string, string]) => readonly [string, string] diff --git a/tests/baselines/reference/recursiveTypeReferences1.types b/tests/baselines/reference/recursiveTypeReferences1.types index 0c7b0fb101e..f402c9f7ef6 100644 --- a/tests/baselines/reference/recursiveTypeReferences1.types +++ b/tests/baselines/reference/recursiveTypeReferences1.types @@ -347,7 +347,7 @@ type T10 = T10[]; >T10 : T10 type T11 = readonly T11[]; ->T11 : readonly (readonly (readonly (readonly (readonly (readonly (readonly (readonly (readonly (readonly (readonly any[])[])[])[])[])[])[])[])[])[])[] +>T11 : T11 type T12 = (T12)[]; >T12 : T12 diff --git a/tests/baselines/reference/reservedWords2.errors.txt b/tests/baselines/reference/reservedWords2.errors.txt index 437b414a69d..05872688b77 100644 --- a/tests/baselines/reference/reservedWords2.errors.txt +++ b/tests/baselines/reference/reservedWords2.errors.txt @@ -4,7 +4,7 @@ tests/cases/compiler/reservedWords2.ts(1,16): error TS2580: Cannot find name 're tests/cases/compiler/reservedWords2.ts(1,31): error TS1005: ')' expected. tests/cases/compiler/reservedWords2.ts(2,12): error TS2300: Duplicate identifier '(Missing)'. tests/cases/compiler/reservedWords2.ts(2,12): error TS2567: Enum declarations can only merge with namespace or other enum declarations. -tests/cases/compiler/reservedWords2.ts(2,14): error TS1003: Identifier expected. +tests/cases/compiler/reservedWords2.ts(2,14): error TS1359: Identifier expected. 'while' is a reserved word that cannot be used here. tests/cases/compiler/reservedWords2.ts(2,20): error TS1005: '(' expected. tests/cases/compiler/reservedWords2.ts(2,20): error TS2304: Cannot find name 'from'. tests/cases/compiler/reservedWords2.ts(2,25): error TS1005: ')' expected. @@ -12,7 +12,7 @@ tests/cases/compiler/reservedWords2.ts(4,5): error TS1134: Variable declaration tests/cases/compiler/reservedWords2.ts(4,12): error TS1109: Expression expected. tests/cases/compiler/reservedWords2.ts(5,9): error TS2300: Duplicate identifier '(Missing)'. tests/cases/compiler/reservedWords2.ts(5,9): error TS2567: Enum declarations can only merge with namespace or other enum declarations. -tests/cases/compiler/reservedWords2.ts(5,10): error TS1003: Identifier expected. +tests/cases/compiler/reservedWords2.ts(5,10): error TS1359: Identifier expected. 'throw' is a reserved word that cannot be used here. tests/cases/compiler/reservedWords2.ts(5,18): error TS1005: '=>' expected. tests/cases/compiler/reservedWords2.ts(6,1): error TS2580: Cannot find name 'module'. Do you need to install type definitions for node? Try `npm i @types/node`. tests/cases/compiler/reservedWords2.ts(6,8): error TS1005: ';' expected. @@ -29,10 +29,13 @@ tests/cases/compiler/reservedWords2.ts(9,14): error TS1005: ';' expected. tests/cases/compiler/reservedWords2.ts(9,18): error TS1005: '(' expected. tests/cases/compiler/reservedWords2.ts(9,20): error TS1128: Declaration or statement expected. tests/cases/compiler/reservedWords2.ts(10,5): error TS2567: Enum declarations can only merge with namespace or other enum declarations. -tests/cases/compiler/reservedWords2.ts(10,6): error TS1003: Identifier expected. +tests/cases/compiler/reservedWords2.ts(10,6): error TS1359: Identifier expected. 'void' is a reserved word that cannot be used here. +tests/cases/compiler/reservedWords2.ts(11,12): error TS1359: Identifier expected. 'default' is a reserved word that cannot be used here. +tests/cases/compiler/reservedWords2.ts(12,13): error TS1359: Identifier expected. 'null' is a reserved word that cannot be used here. +tests/cases/compiler/reservedWords2.ts(12,17): error TS1138: Parameter declaration expected. -==== tests/cases/compiler/reservedWords2.ts (32 errors) ==== +==== tests/cases/compiler/reservedWords2.ts (35 errors) ==== import while = require("dfdf"); ~~~~~ !!! error TS1109: Expression expected. @@ -48,7 +51,7 @@ tests/cases/compiler/reservedWords2.ts(10,6): error TS1003: Identifier expected. !!! error TS2567: Enum declarations can only merge with namespace or other enum declarations. ~~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'while' is a reserved word that cannot be used here. ~~~~ !!! error TS1005: '(' expected. ~~~~ @@ -67,7 +70,7 @@ tests/cases/compiler/reservedWords2.ts(10,6): error TS1003: Identifier expected. !!! error TS2567: Enum declarations can only merge with namespace or other enum declarations. ~~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'throw' is a reserved word that cannot be used here. ~ !!! error TS1005: '=>' expected. module void {} @@ -106,7 +109,14 @@ tests/cases/compiler/reservedWords2.ts(10,6): error TS1003: Identifier expected. !!! error TS2567: Enum declarations can only merge with namespace or other enum declarations. ~~~~ -!!! error TS1003: Identifier expected. - +!!! error TS1359: Identifier expected. 'void' is a reserved word that cannot be used here. + function f(default: number) {} + ~~~~~~~ +!!! error TS1359: Identifier expected. 'default' is a reserved word that cannot be used here. + class C { m(null: string) {} } + ~~~~ +!!! error TS1359: Identifier expected. 'null' is a reserved word that cannot be used here. + ~ +!!! error TS1138: Parameter declaration expected. \ No newline at end of file diff --git a/tests/baselines/reference/reservedWords2.js b/tests/baselines/reference/reservedWords2.js index f172f37d053..49a680085ee 100644 --- a/tests/baselines/reference/reservedWords2.js +++ b/tests/baselines/reference/reservedWords2.js @@ -9,7 +9,8 @@ var {while, return} = { while: 1, return: 2 }; var {this, switch: { continue} } = { this: 1, switch: { continue: 2 }}; var [debugger, if] = [1, 2]; enum void {} - +function f(default: number) {} +class C { m(null: string) {} } @@ -38,3 +39,10 @@ if () (function () { })( || ( = {})); void {}; +function f() { } +var C = /** @class */ (function () { + function C() { + } + C.prototype.m = function (, string) { }; + return C; +}()); diff --git a/tests/baselines/reference/reservedWords2.symbols b/tests/baselines/reference/reservedWords2.symbols index 562b024f313..865ee314ba7 100644 --- a/tests/baselines/reference/reservedWords2.symbols +++ b/tests/baselines/reference/reservedWords2.symbols @@ -30,5 +30,14 @@ var [debugger, if] = [1, 2]; enum void {} > : Symbol((Missing), Decl(reservedWords2.ts, 8, 28)) +function f(default: number) {} +>f : Symbol(f, Decl(reservedWords2.ts, 9, 12)) +> : Symbol((Missing), Decl(reservedWords2.ts, 10, 11)) + +class C { m(null: string) {} } +>C : Symbol(C, Decl(reservedWords2.ts, 10, 30)) +>m : Symbol(C.m, Decl(reservedWords2.ts, 11, 9)) +> : Symbol((Missing), Decl(reservedWords2.ts, 11, 12)) +>string : Symbol(string, Decl(reservedWords2.ts, 11, 17)) diff --git a/tests/baselines/reference/reservedWords2.types b/tests/baselines/reference/reservedWords2.types index 2ec19e01618..abb5717cad3 100644 --- a/tests/baselines/reference/reservedWords2.types +++ b/tests/baselines/reference/reservedWords2.types @@ -64,5 +64,14 @@ enum void {} >void {} : undefined >{} : {} +function f(default: number) {} +>f : (: number) => void +> : number + +class C { m(null: string) {} } +>C : C +>m : (: any, string: any) => void +> : any +>string : any diff --git a/tests/baselines/reference/showConfig/Shows tsconfig for single option/listFilesOnly/tsconfig.json b/tests/baselines/reference/showConfig/Shows tsconfig for single option/listFilesOnly/tsconfig.json new file mode 100644 index 00000000000..9134bd8c6fa --- /dev/null +++ b/tests/baselines/reference/showConfig/Shows tsconfig for single option/listFilesOnly/tsconfig.json @@ -0,0 +1,5 @@ +{ + "compilerOptions": { + "listFilesOnly": true + } +} diff --git a/tests/baselines/reference/symbolProperty17.errors.txt b/tests/baselines/reference/symbolProperty17.errors.txt index 51f77646f0d..a28a1d09810 100644 --- a/tests/baselines/reference/symbolProperty17.errors.txt +++ b/tests/baselines/reference/symbolProperty17.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/Symbols/symbolProperty17.ts(3,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/es6/Symbols/symbolProperty17.ts(3,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/es6/Symbols/symbolProperty17.ts (1 errors) ==== @@ -6,7 +6,7 @@ tests/cases/conformance/es6/Symbols/symbolProperty17.ts(3,6): error TS1023: An i [Symbol.iterator]: number; [s: symbol]: string; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. "__@iterator": string; } diff --git a/tests/baselines/reference/symbolProperty29.errors.txt b/tests/baselines/reference/symbolProperty29.errors.txt index 1efaeb2b3bf..b0f6bb3bc31 100644 --- a/tests/baselines/reference/symbolProperty29.errors.txt +++ b/tests/baselines/reference/symbolProperty29.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/Symbols/symbolProperty29.ts(5,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/es6/Symbols/symbolProperty29.ts(5,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/es6/Symbols/symbolProperty29.ts (1 errors) ==== @@ -8,5 +8,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty29.ts(5,6): error TS1023: An i } [s: symbol]: () => { x: string }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/symbolProperty30.errors.txt b/tests/baselines/reference/symbolProperty30.errors.txt index b839d11d1b8..c986fd28641 100644 --- a/tests/baselines/reference/symbolProperty30.errors.txt +++ b/tests/baselines/reference/symbolProperty30.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/Symbols/symbolProperty30.ts(5,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/es6/Symbols/symbolProperty30.ts(5,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/es6/Symbols/symbolProperty30.ts (1 errors) ==== @@ -8,5 +8,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty30.ts(5,6): error TS1023: An i } [s: symbol]: () => { x: number }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/symbolProperty31.errors.txt b/tests/baselines/reference/symbolProperty31.errors.txt index 39735c017b2..46a61778090 100644 --- a/tests/baselines/reference/symbolProperty31.errors.txt +++ b/tests/baselines/reference/symbolProperty31.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/Symbols/symbolProperty31.ts(7,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/es6/Symbols/symbolProperty31.ts(7,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/es6/Symbols/symbolProperty31.ts (1 errors) ==== @@ -10,5 +10,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty31.ts(7,6): error TS1023: An i class C2 extends C1 { [s: symbol]: () => { x: string }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/symbolProperty32.errors.txt b/tests/baselines/reference/symbolProperty32.errors.txt index 4051f8f91c8..3318459b294 100644 --- a/tests/baselines/reference/symbolProperty32.errors.txt +++ b/tests/baselines/reference/symbolProperty32.errors.txt @@ -1,4 +1,4 @@ -tests/cases/conformance/es6/Symbols/symbolProperty32.ts(7,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/es6/Symbols/symbolProperty32.ts(7,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/es6/Symbols/symbolProperty32.ts (1 errors) ==== @@ -10,5 +10,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty32.ts(7,6): error TS1023: An i class C2 extends C1 { [s: symbol]: () => { x: number }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/symbolProperty33.errors.txt b/tests/baselines/reference/symbolProperty33.errors.txt index 5c23a80f8ca..09b32a501ce 100644 --- a/tests/baselines/reference/symbolProperty33.errors.txt +++ b/tests/baselines/reference/symbolProperty33.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty33.ts(1,18): error TS2449: Class 'C2' used before its declaration. -tests/cases/conformance/es6/Symbols/symbolProperty33.ts(7,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/es6/Symbols/symbolProperty33.ts(7,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/es6/Symbols/symbolProperty33.ts (2 errors) ==== @@ -14,5 +14,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty33.ts(7,6): error TS1023: An i class C2 { [s: symbol]: () => { x: string }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/symbolProperty34.errors.txt b/tests/baselines/reference/symbolProperty34.errors.txt index bd909ae3b68..390ead2177f 100644 --- a/tests/baselines/reference/symbolProperty34.errors.txt +++ b/tests/baselines/reference/symbolProperty34.errors.txt @@ -1,5 +1,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty34.ts(1,18): error TS2449: Class 'C2' used before its declaration. -tests/cases/conformance/es6/Symbols/symbolProperty34.ts(7,6): error TS1023: An index signature parameter type must be 'string' or 'number'. +tests/cases/conformance/es6/Symbols/symbolProperty34.ts(7,6): error TS1023: An index signature parameter type must be either 'string' or 'number'. ==== tests/cases/conformance/es6/Symbols/symbolProperty34.ts (2 errors) ==== @@ -14,5 +14,5 @@ tests/cases/conformance/es6/Symbols/symbolProperty34.ts(7,6): error TS1023: An i class C2 { [s: symbol]: () => { x: number }; ~ -!!! error TS1023: An index signature parameter type must be 'string' or 'number'. +!!! error TS1023: An index signature parameter type must be either 'string' or 'number'. } \ No newline at end of file diff --git a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt index 11d554f39eb..437ec2b15b2 100644 --- a/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt +++ b/tests/baselines/reference/thisTypeInFunctionsNegative.errors.txt @@ -74,15 +74,15 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(158,17): e tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(162,9): error TS2681: A constructor cannot have a 'this' parameter. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(164,31): error TS2681: A constructor cannot have a 'this' parameter. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(165,30): error TS2680: A 'this' parameter must be the first parameter. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(168,26): error TS1003: Identifier expected. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(168,26): error TS1359: Identifier expected. 'this' is a reserved word that cannot be used here. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(168,26): error TS2680: A 'this' parameter must be the first parameter. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(169,23): error TS1003: Identifier expected. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(169,23): error TS1359: Identifier expected. 'this' is a reserved word that cannot be used here. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(169,23): error TS2680: A 'this' parameter must be the first parameter. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(170,23): error TS1005: ',' expected. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(171,28): error TS1003: Identifier expected. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(171,28): error TS1359: Identifier expected. 'this' is a reserved word that cannot be used here. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(171,28): error TS2680: A 'this' parameter must be the first parameter. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,30): error TS1005: ',' expected. -tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,32): error TS1003: Identifier expected. +tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,32): error TS1359: Identifier expected. 'new' is a reserved word that cannot be used here. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,37): error TS1005: ',' expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,38): error TS1109: Expression expected. tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(172,39): error TS1005: ';' expected. @@ -395,12 +395,12 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(178,22): e ///// parse errors ///// function modifiers(async this: C): number { return this.n; } ~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'this' is a reserved word that cannot be used here. ~~~~~~~ !!! error TS2680: A 'this' parameter must be the first parameter. function restParam(...this: C): number { return this.n; } ~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'this' is a reserved word that cannot be used here. ~~~~~~~ !!! error TS2680: A 'this' parameter must be the first parameter. function optional(this?: C): number { return this.n; } @@ -408,14 +408,14 @@ tests/cases/conformance/types/thisType/thisTypeInFunctionsNegative.ts(178,22): e !!! error TS1005: ',' expected. function decorated(@deco() this: C): number { return this.n; } ~~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'this' is a reserved word that cannot be used here. ~~~~~~~ !!! error TS2680: A 'this' parameter must be the first parameter. function initializer(this: C = new C()): number { return this.n; } ~ !!! error TS1005: ',' expected. ~~~ -!!! error TS1003: Identifier expected. +!!! error TS1359: Identifier expected. 'new' is a reserved word that cannot be used here. ~ !!! error TS1005: ',' expected. ~ diff --git a/tests/baselines/reference/thisTypeOptionalCall.js b/tests/baselines/reference/thisTypeOptionalCall.js new file mode 100644 index 00000000000..2a7a24d6eeb --- /dev/null +++ b/tests/baselines/reference/thisTypeOptionalCall.js @@ -0,0 +1,10 @@ +//// [thisTypeOptionalCall.ts] +function maybeBind(obj: T, fn: ((this: T, ...args: A) => R) | undefined): ((...args: A) => R) | undefined { + return fn?.bind(obj); +} + +//// [thisTypeOptionalCall.js] +function maybeBind(obj, fn) { + var _a; + return (_a = fn) === null || _a === void 0 ? void 0 : _a.bind(obj); +} diff --git a/tests/baselines/reference/thisTypeOptionalCall.symbols b/tests/baselines/reference/thisTypeOptionalCall.symbols new file mode 100644 index 00000000000..d55d8c823c1 --- /dev/null +++ b/tests/baselines/reference/thisTypeOptionalCall.symbols @@ -0,0 +1,24 @@ +=== tests/cases/conformance/types/thisType/thisTypeOptionalCall.ts === +function maybeBind(obj: T, fn: ((this: T, ...args: A) => R) | undefined): ((...args: A) => R) | undefined { +>maybeBind : Symbol(maybeBind, Decl(thisTypeOptionalCall.ts, 0, 0)) +>T : Symbol(T, Decl(thisTypeOptionalCall.ts, 0, 19)) +>A : Symbol(A, Decl(thisTypeOptionalCall.ts, 0, 21)) +>R : Symbol(R, Decl(thisTypeOptionalCall.ts, 0, 38)) +>obj : Symbol(obj, Decl(thisTypeOptionalCall.ts, 0, 42)) +>T : Symbol(T, Decl(thisTypeOptionalCall.ts, 0, 19)) +>fn : Symbol(fn, Decl(thisTypeOptionalCall.ts, 0, 49)) +>this : Symbol(this, Decl(thisTypeOptionalCall.ts, 0, 56)) +>T : Symbol(T, Decl(thisTypeOptionalCall.ts, 0, 19)) +>args : Symbol(args, Decl(thisTypeOptionalCall.ts, 0, 64)) +>A : Symbol(A, Decl(thisTypeOptionalCall.ts, 0, 21)) +>R : Symbol(R, Decl(thisTypeOptionalCall.ts, 0, 38)) +>args : Symbol(args, Decl(thisTypeOptionalCall.ts, 0, 99)) +>A : Symbol(A, Decl(thisTypeOptionalCall.ts, 0, 21)) +>R : Symbol(R, Decl(thisTypeOptionalCall.ts, 0, 38)) + + return fn?.bind(obj); +>fn?.bind : Symbol(Function.bind, Decl(lib.es5.d.ts, --, --)) +>fn : Symbol(fn, Decl(thisTypeOptionalCall.ts, 0, 49)) +>bind : Symbol(Function.bind, Decl(lib.es5.d.ts, --, --)) +>obj : Symbol(obj, Decl(thisTypeOptionalCall.ts, 0, 42)) +} diff --git a/tests/baselines/reference/thisTypeOptionalCall.types b/tests/baselines/reference/thisTypeOptionalCall.types new file mode 100644 index 00000000000..1c2a9cd7020 --- /dev/null +++ b/tests/baselines/reference/thisTypeOptionalCall.types @@ -0,0 +1,16 @@ +=== tests/cases/conformance/types/thisType/thisTypeOptionalCall.ts === +function maybeBind(obj: T, fn: ((this: T, ...args: A) => R) | undefined): ((...args: A) => R) | undefined { +>maybeBind : (obj: T, fn: ((this: T, ...args: A) => R) | undefined) => ((...args: A) => R) | undefined +>obj : T +>fn : ((this: T, ...args: A) => R) | undefined +>this : T +>args : A +>args : A + + return fn?.bind(obj); +>fn?.bind(obj) : any +>fn?.bind : ((this: Function, thisArg: any, ...argArray: any[]) => any) | undefined +>fn : ((this: T, ...args: A) => R) | undefined +>bind : ((this: Function, thisArg: any, ...argArray: any[]) => any) | undefined +>obj : T +} diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/modules-and-globals-mixed-in-amd.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/modules-and-globals-mixed-in-amd.js index 156e26088e0..f7e72a97df5 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/modules-and-globals-mixed-in-amd.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/modules-and-globals-mixed-in-amd.js @@ -14,7 +14,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.js] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/multiple-emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/multiple-emitHelpers-in-all-projects.js index e09e87242a1..a8031f00754 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/multiple-emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/multiple-emitHelpers-in-all-projects.js @@ -14,7 +14,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.js] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/multiple-prologues-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/multiple-prologues-in-all-projects.js index 93a7cbf7326..20b15b4d880 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/multiple-prologues-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/multiple-prologues-in-all-projects.js @@ -14,7 +14,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.js] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/shebang-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/shebang-in-all-projects.js index e3daf15bcac..8edcec79d8b 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/shebang-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/shebang-in-all-projects.js @@ -14,7 +14,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.js] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/stripInternal.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/stripInternal.js index 375dd743926..36435d0421c 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/stripInternal.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/stripInternal.js @@ -14,7 +14,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.js] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/triple-slash-refs-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/triple-slash-refs-in-all-projects.js index b07879caae0..de9f9dc4ac5 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/triple-slash-refs-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-declaration-doesnt-change/triple-slash-refs-in-all-projects.js @@ -14,7 +14,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.js] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-all-projects.js index 27bdfed7421..fe117cffae0 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-all-projects.js @@ -14,7 +14,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.js] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/multiple-prologues-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/multiple-prologues-in-all-projects.js index ae8b69e86b9..3d7c28a3a28 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/multiple-prologues-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/multiple-prologues-in-all-projects.js @@ -14,7 +14,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.d.ts.map] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/stripInternal.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/stripInternal.js index e371045db9a..455d2e78174 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/stripInternal.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/incremental-headers-change-without-dts-changes/stripInternal.js @@ -12,7 +12,7 @@ 12:08:00 AM - Updating output of project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.d.ts] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/modules-and-globals-mixed-in-amd.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/modules-and-globals-mixed-in-amd.js index 1e6b3c5f9d3..dbe3eaffbde 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/modules-and-globals-mixed-in-amd.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/modules-and-globals-mixed-in-amd.js @@ -12,7 +12,7 @@ 12:01:00 AM - Building project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.d.ts] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/multiple-emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/multiple-emitHelpers-in-all-projects.js index 4bef255a862..a2965cde2de 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/multiple-emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/multiple-emitHelpers-in-all-projects.js @@ -12,7 +12,7 @@ 12:01:00 AM - Building project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/file3.ts] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/multiple-prologues-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/multiple-prologues-in-all-projects.js index 0a28b0c5003..ce52dcebd47 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/multiple-prologues-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/multiple-prologues-in-all-projects.js @@ -12,7 +12,7 @@ 12:01:00 AM - Building project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/file3.ts] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/shebang-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/shebang-in-all-projects.js index 16c2c89eab9..ac259989bce 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/shebang-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/shebang-in-all-projects.js @@ -12,7 +12,7 @@ 12:01:00 AM - Building project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/file3.ts] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/stripInternal.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/stripInternal.js index 6192e04a062..04bdb8e9b46 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/stripInternal.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/stripInternal.js @@ -12,7 +12,7 @@ 12:01:00 AM - Building project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/module.d.ts] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/triple-slash-refs-in-all-projects.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/triple-slash-refs-in-all-projects.js index 50259e2c93d..3aab51c08f7 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/triple-slash-refs-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/triple-slash-refs-in-all-projects.js @@ -12,7 +12,7 @@ 12:01:00 AM - Building project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/file4.ts] diff --git a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/when-the-module-resolution-finds-original-source-file.js b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/when-the-module-resolution-finds-original-source-file.js index 9bc7340630f..1ddbd2fff9a 100644 --- a/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/when-the-module-resolution-finds-original-source-file.js +++ b/tests/baselines/reference/tsbuild/amdModulesWithOut/initial-build/when-the-module-resolution-finds-original-source-file.js @@ -12,7 +12,7 @@ 12:00:00 AM - Building project '/src/app/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/app/file3.ts] diff --git a/tests/baselines/reference/tsbuild/containerOnlyReferenced/initial-build/verify-that-subsequent-builds-after-initial-build-doesnt-build-anything.js b/tests/baselines/reference/tsbuild/containerOnlyReferenced/initial-build/verify-that-subsequent-builds-after-initial-build-doesnt-build-anything.js new file mode 100644 index 00000000000..d0dedc6b9c1 --- /dev/null +++ b/tests/baselines/reference/tsbuild/containerOnlyReferenced/initial-build/verify-that-subsequent-builds-after-initial-build-doesnt-build-anything.js @@ -0,0 +1,135 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src --verbose +12:01:00 AM - Projects in this build: + * src/src/folder/tsconfig.json + * src/src/folder2/tsconfig.json + * src/src/tsconfig.json + * src/tests/tsconfig.json + * src/tsconfig.json + +12:01:00 AM - Project 'src/src/folder/tsconfig.json' is out of date because output file 'src/src/folder/index.js' does not exist + +12:01:00 AM - Building project '/src/src/folder/tsconfig.json'... + +12:01:00 AM - Project 'src/src/folder2/tsconfig.json' is out of date because output file 'src/src/folder2/index.js' does not exist + +12:01:00 AM - Building project '/src/src/folder2/tsconfig.json'... + +12:01:00 AM - Project 'src/tests/tsconfig.json' is out of date because output file 'src/tests/index.js' does not exist + +12:01:00 AM - Building project '/src/tests/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/src/folder/index.d.ts] +export declare const x = 10; + + +//// [/src/src/folder/index.js] +"use strict"; +exports.__esModule = true; +exports.x = 10; + + +//// [/src/src/folder/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./index.ts": { + "version": "-10726455937-export const x = 10;", + "signature": "-6057683066-export declare const x = 10;\r\n" + } + }, + "options": { + "composite": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../../lib/lib.d.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/src/folder2/index.d.ts] +export declare const x = 10; + + +//// [/src/src/folder2/index.js] +"use strict"; +exports.__esModule = true; +exports.x = 10; + + +//// [/src/src/folder2/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./index.ts": { + "version": "-10726455937-export const x = 10;", + "signature": "-6057683066-export declare const x = 10;\r\n" + } + }, + "options": { + "composite": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../../lib/lib.d.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tests/index.d.ts] +export declare const x = 10; + + +//// [/src/tests/index.js] +"use strict"; +exports.__esModule = true; +exports.x = 10; + + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./index.ts": { + "version": "-10726455937-export const x = 10;", + "signature": "-6057683066-export declare const x = 10;\r\n" + } + }, + "options": { + "composite": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/containerOnlyReferenced/no-change-run/verify-that-subsequent-builds-after-initial-build-doesnt-build-anything.js b/tests/baselines/reference/tsbuild/containerOnlyReferenced/no-change-run/verify-that-subsequent-builds-after-initial-build-doesnt-build-anything.js new file mode 100644 index 00000000000..d47940ed3e2 --- /dev/null +++ b/tests/baselines/reference/tsbuild/containerOnlyReferenced/no-change-run/verify-that-subsequent-builds-after-initial-build-doesnt-build-anything.js @@ -0,0 +1,18 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --b /src --verbose +12:04:00 AM - Projects in this build: + * src/src/folder/tsconfig.json + * src/src/folder2/tsconfig.json + * src/src/tsconfig.json + * src/tests/tsconfig.json + * src/tsconfig.json + +12:04:00 AM - Project 'src/src/folder/tsconfig.json' is up to date because newest input 'src/src/folder/index.ts' is older than oldest output 'src/src/folder/index.js' + +12:04:00 AM - Project 'src/src/folder2/tsconfig.json' is up to date because newest input 'src/src/folder2/index.ts' is older than oldest output 'src/src/folder2/index.js' + +12:04:00 AM - Project 'src/tests/tsconfig.json' is up to date because newest input 'src/tests/index.ts' is older than oldest output 'src/tests/index.js' + +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsbuild/demo/initial-build/in-bad-ref-branch-reports-the-error-about-files-not-in-rootDir-at-the-import-location.js b/tests/baselines/reference/tsbuild/demo/initial-build/in-bad-ref-branch-reports-the-error-about-files-not-in-rootDir-at-the-import-location.js new file mode 100644 index 00000000000..bcc933cdbdb --- /dev/null +++ b/tests/baselines/reference/tsbuild/demo/initial-build/in-bad-ref-branch-reports-the-error-about-files-not-in-rootDir-at-the-import-location.js @@ -0,0 +1,44 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig.json --verbose +12:00:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/animals/tsconfig.json + * src/zoo/tsconfig.json + * src/tsconfig.json + +12:00:00 AM - Project 'src/core/tsconfig.json' is out of date because output file 'src/lib/core/utilities.js' does not exist + +12:00:00 AM - Building project '/src/core/tsconfig.json'... + +src/animals/index.ts(1,20): error TS6059: File '/src/animals/animal.ts' is not under 'rootDir' '/src/core'. 'rootDir' is expected to contain all source files. +src/animals/index.ts(1,20): error TS6307: File '/src/animals/animal.ts' is not listed within the file list of project '/src/core/tsconfig.json'. Projects must list all files or use an 'include' pattern. +src/animals/index.ts(4,32): error TS6059: File '/src/animals/dog.ts' is not under 'rootDir' '/src/core'. 'rootDir' is expected to contain all source files. +src/animals/index.ts(4,32): error TS6307: File '/src/animals/dog.ts' is not listed within the file list of project '/src/core/tsconfig.json'. Projects must list all files or use an 'include' pattern. +src/core/utilities.ts(1,1): error TS6133: 'A' is declared but its value is never read. +src/core/utilities.ts(1,20): error TS6059: File '/src/animals/index.ts' is not under 'rootDir' '/src/core'. 'rootDir' is expected to contain all source files. +src/core/utilities.ts(1,20): error TS6307: File '/src/animals/index.ts' is not listed within the file list of project '/src/core/tsconfig.json'. Projects must list all files or use an 'include' pattern. +12:00:00 AM - Project 'src/animals/tsconfig.json' can't be built because its dependency 'src/core' has errors + +12:00:00 AM - Skipping build of project '/src/animals/tsconfig.json' because its dependency '/src/core' has errors + +12:00:00 AM - Project 'src/zoo/tsconfig.json' can't be built because its dependency 'src/animals' was not built + +12:00:00 AM - Skipping build of project '/src/zoo/tsconfig.json' because its dependency '/src/animals' was not built + +exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped + + +//// [/src/core/utilities.ts] +import * as A from '../animals'; + +export function makeRandomName() { + return "Bob!?! "; +} + +export function lastElementOf(arr: T[]): T | undefined { + if (arr.length === 0) return undefined; + return arr[arr.length - 1]; +} + + + diff --git a/tests/baselines/reference/tsbuild/demo/initial-build/in-circular-branch-reports-the-error-about-it-by-stopping-build.js b/tests/baselines/reference/tsbuild/demo/initial-build/in-circular-branch-reports-the-error-about-it-by-stopping-build.js new file mode 100644 index 00000000000..c7376c362e7 --- /dev/null +++ b/tests/baselines/reference/tsbuild/demo/initial-build/in-circular-branch-reports-the-error-about-it-by-stopping-build.js @@ -0,0 +1,29 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig.json --verbose +12:00:00 AM - Projects in this build: + * src/animals/tsconfig.json + * src/zoo/tsconfig.json + * src/core/tsconfig.json + * src/tsconfig.json + +error TS6202: Project references may not form a circular graph. Cycle detected: /src/tsconfig.json +/src/core/tsconfig.json +/src/zoo/tsconfig.json +/src/animals/tsconfig.json +exitCode:: ExitStatus.ProjectReferenceCycle_OutputsSkupped + + +//// [/src/core/tsconfig.json] +{ + "extends": "../tsconfig-base.json", + "compilerOptions": { + "outDir": "../lib/core", + "rootDir": "." + }, + "references": [ + { + "path": "../zoo" + } + ] +} + diff --git a/tests/baselines/reference/tsbuild/demo/initial-build/in-master-branch-with-everything-setup-correctly-and-reports-no-error.js b/tests/baselines/reference/tsbuild/demo/initial-build/in-master-branch-with-everything-setup-correctly-and-reports-no-error.js new file mode 100644 index 00000000000..f5b45ed2587 --- /dev/null +++ b/tests/baselines/reference/tsbuild/demo/initial-build/in-master-branch-with-everything-setup-correctly-and-reports-no-error.js @@ -0,0 +1,292 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig.json --verbose +12:00:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/animals/tsconfig.json + * src/zoo/tsconfig.json + * src/tsconfig.json + +12:00:00 AM - Project 'src/core/tsconfig.json' is out of date because output file 'src/lib/core/utilities.js' does not exist + +12:00:00 AM - Building project '/src/core/tsconfig.json'... + +12:00:00 AM - Project 'src/animals/tsconfig.json' is out of date because output file 'src/lib/animals/animal.js' does not exist + +12:00:00 AM - Building project '/src/animals/tsconfig.json'... + +12:00:00 AM - Project 'src/zoo/tsconfig.json' is out of date because output file 'src/lib/zoo/zoo.js' does not exist + +12:00:00 AM - Building project '/src/zoo/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/lib/animals/animal.d.ts] +export declare type Size = "small" | "medium" | "large"; +export default interface Animal { + size: Size; +} + + +//// [/src/lib/animals/animal.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); + + +//// [/src/lib/animals/dog.d.ts] +import Animal from '.'; +export interface Dog extends Animal { + woof(): void; + name: string; +} +export declare function createDog(): Dog; + + +//// [/src/lib/animals/dog.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var utilities_1 = require("../core/utilities"); +function createDog() { + return ({ + size: "medium", + woof: function () { + console.log(this.name + " says \"Woof\"!"); + }, + name: utilities_1.makeRandomName() + }); +} +exports.createDog = createDog; + + +//// [/src/lib/animals/index.d.ts] +import Animal from './animal'; +export default Animal; +import { createDog, Dog } from './dog'; +export { createDog, Dog }; + + +//// [/src/lib/animals/index.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var animal_1 = require("./animal"); +var dog_1 = require("./dog"); +exports.createDog = dog_1.createDog; + + +//// [/src/lib/animals/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../../animals/animal.ts": { + "version": "-14984181202-export type Size = \"small\" | \"medium\" | \"large\";\r\nexport default interface Animal {\r\n size: Size;\r\n}\r\n", + "signature": "13427676350-export declare type Size = \"small\" | \"medium\" | \"large\";\r\nexport default interface Animal {\r\n size: Size;\r\n}\r\n" + }, + "../../animals/index.ts": { + "version": "-5382672599-import Animal from './animal';\r\n\r\nexport default Animal;\r\nimport { createDog, Dog } from './dog';\r\nexport { createDog, Dog };\r\n", + "signature": "4477582546-import Animal from './animal';\r\nexport default Animal;\r\nimport { createDog, Dog } from './dog';\r\nexport { createDog, Dog };\r\n" + }, + "../../core/utilities.ts": { + "version": "-8177343116-export declare function makeRandomName(): string;\r\nexport declare function lastElementOf(arr: T[]): T | undefined;\r\n", + "signature": "-8177343116-export declare function makeRandomName(): string;\r\nexport declare function lastElementOf(arr: T[]): T | undefined;\r\n" + }, + "../../animals/dog.ts": { + "version": "-10991948013-import Animal from '.';\r\nimport { makeRandomName } from '../core/utilities';\r\n\r\nexport interface Dog extends Animal {\r\n woof(): void;\r\n name: string;\r\n}\r\n\r\nexport function createDog(): Dog {\r\n return ({\r\n size: \"medium\",\r\n woof: function(this: Dog) {\r\n console.log(`${this.name} says \"Woof\"!`);\r\n },\r\n name: makeRandomName()\r\n });\r\n}\r\n\r\n", + "signature": "10854678623-import Animal from '.';\r\nexport interface Dog extends Animal {\r\n woof(): void;\r\n name: string;\r\n}\r\nexport declare function createDog(): Dog;\r\n" + } + }, + "options": { + "declaration": true, + "target": 1, + "module": 1, + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "composite": true, + "outDir": "./", + "rootDir": "../../animals", + "configFilePath": "../../animals/tsconfig.json" + }, + "referencedMap": { + "../../animals/dog.ts": [ + "../../animals/index.ts", + "../core/utilities.d.ts" + ], + "../../animals/index.ts": [ + "../../animals/animal.ts", + "../../animals/dog.ts" + ] + }, + "exportedModulesMap": { + "../../animals/dog.ts": [ + "../../animals/index.ts" + ], + "../../animals/index.ts": [ + "../../animals/animal.ts", + "../../animals/dog.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../../lib/lib.d.ts", + "../../animals/animal.ts", + "../../animals/dog.ts", + "../../animals/index.ts", + "../../core/utilities.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/lib/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../../core/utilities.ts": { + "version": "25274411612-\r\nexport function makeRandomName() {\r\n return \"Bob!?! \";\r\n}\r\n\r\nexport function lastElementOf(arr: T[]): T | undefined {\r\n if (arr.length === 0) return undefined;\r\n return arr[arr.length - 1];\r\n}\r\n\r\n", + "signature": "-8177343116-export declare function makeRandomName(): string;\r\nexport declare function lastElementOf(arr: T[]): T | undefined;\r\n" + } + }, + "options": { + "declaration": true, + "target": 1, + "module": 1, + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "composite": true, + "outDir": "./", + "rootDir": "../../core", + "configFilePath": "../../core/tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../../lib/lib.d.ts", + "../../core/utilities.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/lib/core/utilities.d.ts] +export declare function makeRandomName(): string; +export declare function lastElementOf(arr: T[]): T | undefined; + + +//// [/src/lib/core/utilities.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +function makeRandomName() { + return "Bob!?! "; +} +exports.makeRandomName = makeRandomName; +function lastElementOf(arr) { + if (arr.length === 0) + return undefined; + return arr[arr.length - 1]; +} +exports.lastElementOf = lastElementOf; + + +//// [/src/lib/zoo/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../../animals/animal.ts": { + "version": "13427676350-export declare type Size = \"small\" | \"medium\" | \"large\";\r\nexport default interface Animal {\r\n size: Size;\r\n}\r\n", + "signature": "13427676350-export declare type Size = \"small\" | \"medium\" | \"large\";\r\nexport default interface Animal {\r\n size: Size;\r\n}\r\n" + }, + "../../animals/dog.ts": { + "version": "10854678623-import Animal from '.';\r\nexport interface Dog extends Animal {\r\n woof(): void;\r\n name: string;\r\n}\r\nexport declare function createDog(): Dog;\r\n", + "signature": "10854678623-import Animal from '.';\r\nexport interface Dog extends Animal {\r\n woof(): void;\r\n name: string;\r\n}\r\nexport declare function createDog(): Dog;\r\n" + }, + "../../animals/index.ts": { + "version": "4477582546-import Animal from './animal';\r\nexport default Animal;\r\nimport { createDog, Dog } from './dog';\r\nexport { createDog, Dog };\r\n", + "signature": "4477582546-import Animal from './animal';\r\nexport default Animal;\r\nimport { createDog, Dog } from './dog';\r\nexport { createDog, Dog };\r\n" + }, + "../../zoo/zoo.ts": { + "version": "8797123924-import { Dog, createDog } from '../animals/index';\r\n\r\nexport function createZoo(): Array {\r\n return [\r\n createDog()\r\n ];\r\n}\r\n\r\n", + "signature": "-17433436879-import { Dog } from '../animals/index';\r\nexport declare function createZoo(): Array;\r\n" + } + }, + "options": { + "declaration": true, + "target": 1, + "module": 1, + "strict": true, + "noUnusedLocals": true, + "noUnusedParameters": true, + "noImplicitReturns": true, + "noFallthroughCasesInSwitch": true, + "composite": true, + "outDir": "./", + "rootDir": "../../zoo", + "configFilePath": "../../zoo/tsconfig.json" + }, + "referencedMap": { + "../../animals/dog.ts": [ + "../animals/index.d.ts" + ], + "../../animals/index.ts": [ + "../animals/animal.d.ts", + "../animals/dog.d.ts" + ], + "../../zoo/zoo.ts": [ + "../animals/index.d.ts" + ] + }, + "exportedModulesMap": { + "../../animals/dog.ts": [ + "../animals/index.d.ts" + ], + "../../animals/index.ts": [ + "../animals/animal.d.ts", + "../animals/dog.d.ts" + ], + "../../zoo/zoo.ts": [ + "../animals/index.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../../lib/lib.d.ts", + "../../animals/animal.ts", + "../../animals/dog.ts", + "../../animals/index.ts", + "../../zoo/zoo.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/lib/zoo/zoo.d.ts] +import { Dog } from '../animals/index'; +export declare function createZoo(): Array; + + +//// [/src/lib/zoo/zoo.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var index_1 = require("../animals/index"); +function createZoo() { + return [ + index_1.createDog() + ]; +} +exports.createZoo = createZoo; + + diff --git a/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-circular-import-project-with-emitDeclarationOnly-and-declarationMap.js b/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-circular-import-project-with-emitDeclarationOnly-and-declarationMap.js index d2d70c1b8be..41f2beaa281 100644 --- a/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-circular-import-project-with-emitDeclarationOnly-and-declarationMap.js +++ b/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-circular-import-project-with-emitDeclarationOnly-and-declarationMap.js @@ -7,7 +7,7 @@ 12:04:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/lib/a.d.ts] diff --git a/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-circular-import-project-with-emitDeclarationOnly.js b/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-circular-import-project-with-emitDeclarationOnly.js index 6e6f2bb1805..747e3ee3a36 100644 --- a/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-circular-import-project-with-emitDeclarationOnly.js +++ b/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-circular-import-project-with-emitDeclarationOnly.js @@ -7,7 +7,7 @@ 12:04:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/lib/a.d.ts] diff --git a/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js b/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js index 8bcb33bced7..3ce9402fb24 100644 --- a/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js +++ b/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-changes/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js @@ -7,7 +7,7 @@ 12:04:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/lib/a.d.ts] diff --git a/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-doesnt-change/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js b/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-doesnt-change/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js index bdfcb1e826f..1ab42631bc3 100644 --- a/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-doesnt-change/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js +++ b/tests/baselines/reference/tsbuild/emitDeclarationOnly/incremental-declaration-doesnt-change/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js @@ -9,7 +9,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/lib/a.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-circular-import-project-with-emitDeclarationOnly-and-declarationMap.js b/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-circular-import-project-with-emitDeclarationOnly-and-declarationMap.js index 38d8974e900..6acd9f13604 100644 --- a/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-circular-import-project-with-emitDeclarationOnly-and-declarationMap.js +++ b/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-circular-import-project-with-emitDeclarationOnly-and-declarationMap.js @@ -7,7 +7,7 @@ 12:01:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/lib/a.d.ts] diff --git a/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-circular-import-project-with-emitDeclarationOnly.js b/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-circular-import-project-with-emitDeclarationOnly.js index 6f2bc263212..b854647cbed 100644 --- a/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-circular-import-project-with-emitDeclarationOnly.js +++ b/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-circular-import-project-with-emitDeclarationOnly.js @@ -7,7 +7,7 @@ 12:01:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/lib/a.d.ts] diff --git a/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js b/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js index aabaf41d53b..679a7c01703 100644 --- a/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js +++ b/tests/baselines/reference/tsbuild/emitDeclarationOnly/initial-build/only-dts-output-in-non-circular-imports-project-with-emitDeclarationOnly.js @@ -7,7 +7,7 @@ 12:01:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/lib/a.d.ts] diff --git a/tests/baselines/reference/tsbuild/emptyFiles/initial-build/does-not-have-empty-files-diagnostic-when-files-is-empty-and-references-are-provided.js b/tests/baselines/reference/tsbuild/emptyFiles/initial-build/does-not-have-empty-files-diagnostic-when-files-is-empty-and-references-are-provided.js new file mode 100644 index 00000000000..8760280f3de --- /dev/null +++ b/tests/baselines/reference/tsbuild/emptyFiles/initial-build/does-not-have-empty-files-diagnostic-when-files-is-empty-and-references-are-provided.js @@ -0,0 +1,49 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/with-references +exitCode:: ExitStatus.Success + + +//// [/src/core/index.d.ts] +export declare function multiply(a: number, b: number): number; +//# sourceMappingURL=index.d.ts.map + +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./index.ts": { + "version": "5112841898-export function multiply(a: number, b: number) { return a * b; }\r\n", + "signature": "3361149553-export declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + } + }, + "options": { + "composite": true, + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/emptyFiles/initial-build/has-empty-files-diagnostic-when-files-is-empty-and-no-references-are-provided.js b/tests/baselines/reference/tsbuild/emptyFiles/initial-build/has-empty-files-diagnostic-when-files-is-empty-and-no-references-are-provided.js new file mode 100644 index 00000000000..6db6e8fe608 --- /dev/null +++ b/tests/baselines/reference/tsbuild/emptyFiles/initial-build/has-empty-files-diagnostic-when-files-is-empty-and-no-references-are-provided.js @@ -0,0 +1,6 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/no-references +src/no-references/tsconfig.json(3,14): error TS18002: The 'files' list in config file '/src/no-references/tsconfig.json' is empty. +exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped + + diff --git a/tests/baselines/reference/tsbuild/exitCodeOnBogusFile/initial-build/test-exit-code.js b/tests/baselines/reference/tsbuild/exitCodeOnBogusFile/initial-build/test-exit-code.js new file mode 100644 index 00000000000..eb94c8cd71c --- /dev/null +++ b/tests/baselines/reference/tsbuild/exitCodeOnBogusFile/initial-build/test-exit-code.js @@ -0,0 +1,6 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc -b bogus.json +error TS6053: File '/bogus.json' not found. +exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped + + diff --git a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module-with-isolatedModules.js b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module-with-isolatedModules.js index a95215cf77f..bfe04451775 100644 --- a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module-with-isolatedModules.js +++ b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module-with-isolatedModules.js @@ -9,7 +9,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/bar.ts] diff --git a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module.js b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module.js index 5cd9097a200..4e7610dc52f 100644 --- a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module.js +++ b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/inferred-type-from-transitive-module.js @@ -9,7 +9,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/bar.ts] diff --git a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/reports-errors-in-files-affected-by-change-in-signature-with-isolatedModules.js b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/reports-errors-in-files-affected-by-change-in-signature-with-isolatedModules.js index a00425b57a8..2462f65292e 100644 --- a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/reports-errors-in-files-affected-by-change-in-signature-with-isolatedModules.js +++ b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/incremental-declaration-changes/reports-errors-in-files-affected-by-change-in-signature-with-isolatedModules.js @@ -8,7 +8,7 @@ 12:04:00 AM - Building project '/src/tsconfig.json'... src/lazyIndex.ts(4,5): error TS2554: Expected 0 arguments, but got 1. -exitCode:: 1 +exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped //// [/src/bar.ts] diff --git a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/inferred-type-from-transitive-module-with-isolatedModules.js b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/inferred-type-from-transitive-module-with-isolatedModules.js index 93a7e296495..4d98599a17f 100644 --- a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/inferred-type-from-transitive-module-with-isolatedModules.js +++ b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/inferred-type-from-transitive-module-with-isolatedModules.js @@ -7,7 +7,7 @@ 12:01:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/obj/bar.d.ts] diff --git a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/inferred-type-from-transitive-module.js b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/inferred-type-from-transitive-module.js index 45a284dc09c..584c54a32c9 100644 --- a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/inferred-type-from-transitive-module.js +++ b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/inferred-type-from-transitive-module.js @@ -7,7 +7,7 @@ 12:01:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/obj/bar.d.ts] diff --git a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/reports-errors-in-files-affected-by-change-in-signature-with-isolatedModules.js b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/reports-errors-in-files-affected-by-change-in-signature-with-isolatedModules.js index 39ad2d40a31..4835be06a9e 100644 --- a/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/reports-errors-in-files-affected-by-change-in-signature-with-isolatedModules.js +++ b/tests/baselines/reference/tsbuild/inferredTypeFromTransitiveModule/initial-build/reports-errors-in-files-affected-by-change-in-signature-with-isolatedModules.js @@ -7,7 +7,7 @@ 12:01:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/lazyIndex.ts] diff --git a/tests/baselines/reference/tsbuild/javascriptProjectEmit/incremental-declaration-doesnt-change/modifies-outfile-js-projects-and-concatenates-them-correctly.js b/tests/baselines/reference/tsbuild/javascriptProjectEmit/incremental-declaration-doesnt-change/modifies-outfile-js-projects-and-concatenates-them-correctly.js index b863d923b66..22e8a88b84e 100644 --- a/tests/baselines/reference/tsbuild/javascriptProjectEmit/incremental-declaration-doesnt-change/modifies-outfile-js-projects-and-concatenates-them-correctly.js +++ b/tests/baselines/reference/tsbuild/javascriptProjectEmit/incremental-declaration-doesnt-change/modifies-outfile-js-projects-and-concatenates-them-correctly.js @@ -1,6 +1,6 @@ //// [/lib/incremental-declaration-doesnt-changeOutput.txt] /lib/tsc -b /src -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/sub-project/index.js] diff --git a/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-js-based-projects-and-emits-them-correctly.js b/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-js-based-projects-and-emits-them-correctly.js index 2abc5b9119b..7417b51952a 100644 --- a/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-js-based-projects-and-emits-them-correctly.js +++ b/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-js-based-projects-and-emits-them-correctly.js @@ -47,7 +47,7 @@ module.exports = {}; //// [/lib/initial-buildOutput.txt] /lib/tsc -b /src -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/lib/sub-project/index.d.ts] diff --git a/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-js-based-projects-with-non-moved-json-files-and-emits-them-correctly.js b/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-js-based-projects-with-non-moved-json-files-and-emits-them-correctly.js index 42b47203406..3c49c99688d 100644 --- a/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-js-based-projects-with-non-moved-json-files-and-emits-them-correctly.js +++ b/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-js-based-projects-with-non-moved-json-files-and-emits-them-correctly.js @@ -1,6 +1,6 @@ //// [/lib/initial-buildOutput.txt] /lib/tsc -b /src -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/out/sub-project/index.d.ts] diff --git a/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-outfile-js-projects-and-concatenates-them-correctly.js b/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-outfile-js-projects-and-concatenates-them-correctly.js index c46f5e3baa1..769da514d2e 100644 --- a/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-outfile-js-projects-and-concatenates-them-correctly.js +++ b/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/loads-outfile-js-projects-and-concatenates-them-correctly.js @@ -1,6 +1,6 @@ //// [/lib/initial-buildOutput.txt] /lib/tsc -b /src -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/common/common.d.ts] diff --git a/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/modifies-outfile-js-projects-and-concatenates-them-correctly.js b/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/modifies-outfile-js-projects-and-concatenates-them-correctly.js index c46f5e3baa1..769da514d2e 100644 --- a/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/modifies-outfile-js-projects-and-concatenates-them-correctly.js +++ b/tests/baselines/reference/tsbuild/javascriptProjectEmit/initial-build/modifies-outfile-js-projects-and-concatenates-them-correctly.js @@ -1,6 +1,6 @@ //// [/lib/initial-buildOutput.txt] /lib/tsc -b /src -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/common/common.d.ts] diff --git a/tests/baselines/reference/tsbuild/lateBoundSymbol/incremental-declaration-doesnt-change/interface-is-merged-and-contains-late-bound-member.js b/tests/baselines/reference/tsbuild/lateBoundSymbol/incremental-declaration-doesnt-change/interface-is-merged-and-contains-late-bound-member.js index ffa834ba467..1cdbffe6cc6 100644 --- a/tests/baselines/reference/tsbuild/lateBoundSymbol/incremental-declaration-doesnt-change/interface-is-merged-and-contains-late-bound-member.js +++ b/tests/baselines/reference/tsbuild/lateBoundSymbol/incremental-declaration-doesnt-change/interface-is-merged-and-contains-late-bound-member.js @@ -9,7 +9,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/src/main.js] diff --git a/tests/baselines/reference/tsbuild/lateBoundSymbol/initial-build/interface-is-merged-and-contains-late-bound-member.js b/tests/baselines/reference/tsbuild/lateBoundSymbol/initial-build/interface-is-merged-and-contains-late-bound-member.js index 86d36097454..d89b3a9c894 100644 --- a/tests/baselines/reference/tsbuild/lateBoundSymbol/initial-build/interface-is-merged-and-contains-late-bound-member.js +++ b/tests/baselines/reference/tsbuild/lateBoundSymbol/initial-build/interface-is-merged-and-contains-late-bound-member.js @@ -7,7 +7,7 @@ 12:01:00 AM - Building project '/src/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/src/hkt.js] diff --git a/tests/baselines/reference/tsbuild/missingExtendedConfig/initial-build/when-tsconfig-extends-the-missing-file.js b/tests/baselines/reference/tsbuild/missingExtendedConfig/initial-build/when-tsconfig-extends-the-missing-file.js new file mode 100644 index 00000000000..1221147bc8e --- /dev/null +++ b/tests/baselines/reference/tsbuild/missingExtendedConfig/initial-build/when-tsconfig-extends-the-missing-file.js @@ -0,0 +1,9 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig.json +error TS5058: The specified path does not exist: '/src/foobar.json'. +error TS18003: No inputs were found in config file '/src/tsconfig.first.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '[]'. +error TS5058: The specified path does not exist: '/src/foobar.json'. +error TS18003: No inputs were found in config file '/src/tsconfig.second.json'. Specified 'include' paths were '["**/*"]' and 'exclude' paths were '[]'. +exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped + + diff --git a/tests/baselines/reference/tsbuild/moduleSpecifiers/initial-build/synthesized-module-specifiers-resolve-correctly.js b/tests/baselines/reference/tsbuild/moduleSpecifiers/initial-build/synthesized-module-specifiers-resolve-correctly.js index fb5eae55d7c..5c8f8da7b6f 100644 --- a/tests/baselines/reference/tsbuild/moduleSpecifiers/initial-build/synthesized-module-specifiers-resolve-correctly.js +++ b/tests/baselines/reference/tsbuild/moduleSpecifiers/initial-build/synthesized-module-specifiers-resolve-correctly.js @@ -19,7 +19,7 @@ 12:00:00 AM - Building project '/src/solution/sub-project-2/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/lib/solution/common/nominal.d.ts] diff --git a/tests/baselines/reference/tsbuild/outFile/initial-build/clean-projects.js b/tests/baselines/reference/tsbuild/outFile/initial-build/clean-projects.js new file mode 100644 index 00000000000..619b5b54656 --- /dev/null +++ b/tests/baselines/reference/tsbuild/outFile/initial-build/clean-projects.js @@ -0,0 +1,20 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/third --clean +exitCode:: ExitStatus.Success + + +//// [/src/2/second-output.d.ts] unlink +//// [/src/2/second-output.d.ts.map] unlink +//// [/src/2/second-output.js] unlink +//// [/src/2/second-output.js.map] unlink +//// [/src/2/second-output.tsbuildinfo] unlink +//// [/src/first/bin/first-output.d.ts] unlink +//// [/src/first/bin/first-output.d.ts.map] unlink +//// [/src/first/bin/first-output.js] unlink +//// [/src/first/bin/first-output.js.map] unlink +//// [/src/first/bin/first-output.tsbuildinfo] unlink +//// [/src/third/thirdjs/output/third-output.d.ts] unlink +//// [/src/third/thirdjs/output/third-output.d.ts.map] unlink +//// [/src/third/thirdjs/output/third-output.js] unlink +//// [/src/third/thirdjs/output/third-output.js.map] unlink +//// [/src/third/thirdjs/output/third-output.tsbuildinfo] unlink diff --git a/tests/baselines/reference/tsbuild/outFile/initial-build/non-module-projects-without-prepend.js b/tests/baselines/reference/tsbuild/outFile/initial-build/non-module-projects-without-prepend.js new file mode 100644 index 00000000000..6fde70fe4cf --- /dev/null +++ b/tests/baselines/reference/tsbuild/outFile/initial-build/non-module-projects-without-prepend.js @@ -0,0 +1,334 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/third --verbose +12:00:00 AM - Projects in this build: + * src/first/tsconfig.json + * src/second/tsconfig.json + * src/third/tsconfig.json + +12:00:00 AM - Project 'src/first/tsconfig.json' is out of date because output file 'src/first/first_PART1.js' does not exist + +12:00:00 AM - Building project '/src/first/tsconfig.json'... + +12:00:00 AM - Project 'src/second/tsconfig.json' is out of date because output file 'src/second/second_part1.js' does not exist + +12:00:00 AM - Building project '/src/second/tsconfig.json'... + +12:00:00 AM - Project 'src/third/tsconfig.json' is out of date because output file 'src/third/third_part1.js' does not exist + +12:00:00 AM - Building project '/src/third/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/first/first_PART1.d.ts] +interface TheFirst { + none: any; +} +declare const s = "Hello, world"; +interface NoJsForHereEither { + none: any; +} +//# sourceMappingURL=first_PART1.d.ts.map + +//// [/src/first/first_PART1.d.ts.map] +{"version":3,"file":"first_PART1.d.ts","sourceRoot":"","sources":["first_PART1.ts"],"names":[],"mappings":"AAAA,UAAU,QAAQ;IACd,IAAI,EAAE,GAAG,CAAC;CACb;AAED,QAAA,MAAM,CAAC,iBAAiB,CAAC;AAEzB,UAAU,iBAAiB;IACvB,IAAI,EAAE,GAAG,CAAC;CACb"} + +//// [/src/first/first_PART1.js] +var s = "Hello, world"; +console.log(s); +//# sourceMappingURL=first_PART1.js.map + +//// [/src/first/first_PART1.js.map] +{"version":3,"file":"first_PART1.js","sourceRoot":"","sources":["first_PART1.ts"],"names":[],"mappings":"AAIA,IAAM,CAAC,GAAG,cAAc,CAAC;AAMzB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC"} + +//// [/src/first/first_part2.d.ts] +//# sourceMappingURL=first_part2.d.ts.map + +//// [/src/first/first_part2.d.ts.map] +{"version":3,"file":"first_part2.d.ts","sourceRoot":"","sources":["first_part2.ts"],"names":[],"mappings":""} + +//// [/src/first/first_part2.js] +console.log(f()); +//# sourceMappingURL=first_part2.js.map + +//// [/src/first/first_part2.js.map] +{"version":3,"file":"first_part2.js","sourceRoot":"","sources":["first_part2.ts"],"names":[],"mappings":"AAAA,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC"} + +//// [/src/first/first_part3.d.ts] +declare function f(): string; +//# sourceMappingURL=first_part3.d.ts.map + +//// [/src/first/first_part3.d.ts.map] +{"version":3,"file":"first_part3.d.ts","sourceRoot":"","sources":["first_part3.ts"],"names":[],"mappings":"AAAA,iBAAS,CAAC,WAET"} + +//// [/src/first/first_part3.js] +function f() { + return "JS does hoists"; +} +//# sourceMappingURL=first_part3.js.map + +//// [/src/first/first_part3.js.map] +{"version":3,"file":"first_part3.js","sourceRoot":"","sources":["first_part3.ts"],"names":[],"mappings":"AAAA,SAAS,CAAC;IACN,OAAO,gBAAgB,CAAC;AAC5B,CAAC"} + +//// [/src/first/tsconfig.json] +{ + "compilerOptions": { + "target": "es5", + "composite": true, "module": "none", + "removeComments": true, + "strict": false, + "sourceMap": true, + "declarationMap": true, + + "skipDefaultLibCheck": true + }, + "files": [ + "first_PART1.ts", + "first_part2.ts", + "first_part3.ts" + ], + "references": [ + ] +} + + +//// [/src/first/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./first_part1.ts": { + "version": "-17207381411-interface TheFirst {\r\n none: any;\r\n}\r\n\r\nconst s = \"Hello, world\";\r\n\r\ninterface NoJsForHereEither {\r\n none: any;\r\n}\r\n\r\nconsole.log(s);\r\n", + "signature": "-17939996161-interface TheFirst {\r\n none: any;\r\n}\r\ndeclare const s = \"Hello, world\";\r\ninterface NoJsForHereEither {\r\n none: any;\r\n}\r\n//# sourceMappingURL=first_PART1.d.ts.map" + }, + "./first_part2.ts": { + "version": "4973778178-console.log(f());\r\n", + "signature": "-2054710634-//# sourceMappingURL=first_part2.d.ts.map" + }, + "./first_part3.ts": { + "version": "6202806249-function f() {\r\n return \"JS does hoists\";\r\n}", + "signature": "-4577888121-declare function f(): string;\r\n//# sourceMappingURL=first_part3.d.ts.map" + } + }, + "options": { + "target": 1, + "composite": true, + "module": 0, + "removeComments": true, + "strict": false, + "sourceMap": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./first_part1.ts", + "./first_part2.ts", + "./first_part3.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/second/second_part1.d.ts] +declare namespace N { +} +declare namespace N { +} +//# sourceMappingURL=second_part1.d.ts.map + +//// [/src/second/second_part1.d.ts.map] +{"version":3,"file":"second_part1.d.ts","sourceRoot":"","sources":["second_part1.ts"],"names":[],"mappings":"AAAA,kBAAU,CAAC,CAAC;CAEX;AAED,kBAAU,CAAC,CAAC;CAMX"} + +//// [/src/second/second_part1.js] +var N; +(function (N) { + function f() { + console.log('testing'); + } + f(); +})(N || (N = {})); +//# sourceMappingURL=second_part1.js.map + +//// [/src/second/second_part1.js.map] +{"version":3,"file":"second_part1.js","sourceRoot":"","sources":["second_part1.ts"],"names":[],"mappings":"AAIA,IAAU,CAAC,CAMV;AAND,WAAU,CAAC;IACP,SAAS,CAAC;QACN,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC3B,CAAC;IAED,CAAC,EAAE,CAAC;AACR,CAAC,EANS,CAAC,KAAD,CAAC,QAMV"} + +//// [/src/second/second_part2.d.ts] +declare class C { + doSomething(): void; +} +//# sourceMappingURL=second_part2.d.ts.map + +//// [/src/second/second_part2.d.ts.map] +{"version":3,"file":"second_part2.d.ts","sourceRoot":"","sources":["second_part2.ts"],"names":[],"mappings":"AAAA,cAAM,CAAC;IACH,WAAW;CAGd"} + +//// [/src/second/second_part2.js] +var C = (function () { + function C() { + } + C.prototype.doSomething = function () { + console.log("something got done"); + }; + return C; +}()); +//# sourceMappingURL=second_part2.js.map + +//// [/src/second/second_part2.js.map] +{"version":3,"file":"second_part2.js","sourceRoot":"","sources":["second_part2.ts"],"names":[],"mappings":"AAAA;IAAA;IAIA,CAAC;IAHG,uBAAW,GAAX;QACI,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IACtC,CAAC;IACL,QAAC;AAAD,CAAC,AAJD,IAIC"} + +//// [/src/second/tsconfig.json] +{ + "compilerOptions": { + "target": "es5", + "composite": true, "module": "none", + "removeComments": true, + "strict": false, + "sourceMap": true, + "declarationMap": true, + "declaration": true, + + "skipDefaultLibCheck": true + }, + "references": [ + ] +} + + +//// [/src/second/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./second_part1.ts": { + "version": "-21603042336-namespace N {\r\n // Comment text\r\n}\r\n\r\nnamespace N {\r\n function f() {\r\n console.log('testing');\r\n }\r\n\r\n f();\r\n}\r\n", + "signature": "-3134340341-declare namespace N {\r\n}\r\ndeclare namespace N {\r\n}\r\n//# sourceMappingURL=second_part1.d.ts.map" + }, + "./second_part2.ts": { + "version": "9339262372-class C {\r\n doSomething() {\r\n console.log(\"something got done\");\r\n }\r\n}\r\n", + "signature": "6579734441-declare class C {\r\n doSomething(): void;\r\n}\r\n//# sourceMappingURL=second_part2.d.ts.map" + } + }, + "options": { + "target": 1, + "composite": true, + "module": 0, + "removeComments": true, + "strict": false, + "sourceMap": true, + "declarationMap": true, + "declaration": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./second_part1.ts", + "./second_part2.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/third/third_part1.d.ts] +declare var c: C; +//# sourceMappingURL=third_part1.d.ts.map + +//// [/src/third/third_part1.d.ts.map] +{"version":3,"file":"third_part1.d.ts","sourceRoot":"","sources":["third_part1.ts"],"names":[],"mappings":"AAAA,QAAA,IAAI,CAAC,GAAU,CAAC"} + +//// [/src/third/third_part1.js] +var c = new C(); +c.doSomething(); +//# sourceMappingURL=third_part1.js.map + +//// [/src/third/third_part1.js.map] +{"version":3,"file":"third_part1.js","sourceRoot":"","sources":["third_part1.ts"],"names":[],"mappings":"AAAA,IAAI,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;AAChB,CAAC,CAAC,WAAW,EAAE,CAAC"} + +//// [/src/third/tsconfig.json] +{ + "compilerOptions": { + "target": "es5", + "composite": true, "module": "none", + "removeComments": true, + "strict": false, + "sourceMap": true, + "declarationMap": true, + "declaration": true, + + "skipDefaultLibCheck": true + }, + "files": [ + "third_part1.ts" + ], + "references": [ + { "path": "../first" }, + { "path": "../second" }, + ] +} + + +//// [/src/third/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../first/first_part1.d.ts": { + "version": "-17939996161-interface TheFirst {\r\n none: any;\r\n}\r\ndeclare const s = \"Hello, world\";\r\ninterface NoJsForHereEither {\r\n none: any;\r\n}\r\n//# sourceMappingURL=first_PART1.d.ts.map", + "signature": "-17939996161-interface TheFirst {\r\n none: any;\r\n}\r\ndeclare const s = \"Hello, world\";\r\ninterface NoJsForHereEither {\r\n none: any;\r\n}\r\n//# sourceMappingURL=first_PART1.d.ts.map" + }, + "../first/first_part2.d.ts": { + "version": "-2054710634-//# sourceMappingURL=first_part2.d.ts.map", + "signature": "-2054710634-//# sourceMappingURL=first_part2.d.ts.map" + }, + "../first/first_part3.d.ts": { + "version": "-4577888121-declare function f(): string;\r\n//# sourceMappingURL=first_part3.d.ts.map", + "signature": "-4577888121-declare function f(): string;\r\n//# sourceMappingURL=first_part3.d.ts.map" + }, + "../second/second_part1.d.ts": { + "version": "-3134340341-declare namespace N {\r\n}\r\ndeclare namespace N {\r\n}\r\n//# sourceMappingURL=second_part1.d.ts.map", + "signature": "-3134340341-declare namespace N {\r\n}\r\ndeclare namespace N {\r\n}\r\n//# sourceMappingURL=second_part1.d.ts.map" + }, + "../second/second_part2.d.ts": { + "version": "6579734441-declare class C {\r\n doSomething(): void;\r\n}\r\n//# sourceMappingURL=second_part2.d.ts.map", + "signature": "6579734441-declare class C {\r\n doSomething(): void;\r\n}\r\n//# sourceMappingURL=second_part2.d.ts.map" + }, + "./third_part1.ts": { + "version": "10470273651-var c = new C();\r\nc.doSomething();\r\n", + "signature": "2019699827-declare var c: C;\r\n//# sourceMappingURL=third_part1.d.ts.map" + } + }, + "options": { + "target": 1, + "composite": true, + "module": 0, + "removeComments": true, + "strict": false, + "sourceMap": true, + "declarationMap": true, + "declaration": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../first/first_part1.d.ts", + "../first/first_part2.d.ts", + "../first/first_part3.d.ts", + "../second/second_part1.d.ts", + "../second/second_part2.d.ts", + "./third_part1.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/outFile/initial-build/tsbuildinfo-is-not-generated-when-incremental-is-set-to-false.js b/tests/baselines/reference/tsbuild/outFile/initial-build/tsbuildinfo-is-not-generated-when-incremental-is-set-to-false.js new file mode 100644 index 00000000000..30fe2be5a86 --- /dev/null +++ b/tests/baselines/reference/tsbuild/outFile/initial-build/tsbuildinfo-is-not-generated-when-incremental-is-set-to-false.js @@ -0,0 +1,281 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/third --verbose +12:00:00 AM - Projects in this build: + * src/first/tsconfig.json + * src/second/tsconfig.json + * src/third/tsconfig.json + +12:00:00 AM - Project 'src/first/tsconfig.json' is out of date because output file 'src/first/bin/first-output.js' does not exist + +12:00:00 AM - Building project '/src/first/tsconfig.json'... + +12:00:00 AM - Project 'src/second/tsconfig.json' is out of date because output file 'src/2/second-output.js' does not exist + +12:00:00 AM - Building project '/src/second/tsconfig.json'... + +12:00:00 AM - Project 'src/third/tsconfig.json' is out of date because output file 'src/third/thirdjs/output/third-output.js' does not exist + +12:00:00 AM - Building project '/src/third/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/2/second-output.d.ts] +declare namespace N { +} +declare namespace N { +} +declare class C { + doSomething(): void; +} +//# sourceMappingURL=second-output.d.ts.map + +//// [/src/2/second-output.d.ts.map] +{"version":3,"file":"second-output.d.ts","sourceRoot":"","sources":["../second/second_part1.ts","../second/second_part2.ts"],"names":[],"mappings":"AAAA,kBAAU,CAAC,CAAC;CAEX;AAED,kBAAU,CAAC,CAAC;CAMX;ACVD,cAAM,CAAC;IACH,WAAW;CAGd"} + +//// [/src/2/second-output.js] +var N; +(function (N) { + function f() { + console.log('testing'); + } + f(); +})(N || (N = {})); +var C = (function () { + function C() { + } + C.prototype.doSomething = function () { + console.log("something got done"); + }; + return C; +}()); +//# sourceMappingURL=second-output.js.map + +//// [/src/2/second-output.js.map] +{"version":3,"file":"second-output.js","sourceRoot":"","sources":["../second/second_part1.ts","../second/second_part2.ts"],"names":[],"mappings":"AAIA,IAAU,CAAC,CAMV;AAND,WAAU,CAAC;IACP,SAAS,CAAC;QACN,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC3B,CAAC;IAED,CAAC,EAAE,CAAC;AACR,CAAC,EANS,CAAC,KAAD,CAAC,QAMV;ACVD;IAAA;IAIA,CAAC;IAHG,uBAAW,GAAX;QACI,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IACtC,CAAC;IACL,QAAC;AAAD,CAAC,AAJD,IAIC"} + +//// [/src/2/second-output.tsbuildinfo] +{ + "bundle": { + "commonSourceDirectory": "../second", + "sourceFiles": [ + "../second/second_part1.ts", + "../second/second_part2.ts" + ], + "js": { + "sections": [ + { + "pos": 0, + "end": 285, + "kind": "text" + } + ] + }, + "dts": { + "sections": [ + { + "pos": 0, + "end": 100, + "kind": "text" + } + ] + } + }, + "version": "FakeTSVersion" +} + +//// [/src/2/second-output.tsbuildinfo.baseline.txt] +====================================================================== +File:: /src/2/second-output.js +---------------------------------------------------------------------- +text: (0-285) +var N; +(function (N) { + function f() { + console.log('testing'); + } + f(); +})(N || (N = {})); +var C = (function () { + function C() { + } + C.prototype.doSomething = function () { + console.log("something got done"); + }; + return C; +}()); + +====================================================================== +====================================================================== +File:: /src/2/second-output.d.ts +---------------------------------------------------------------------- +text: (0-100) +declare namespace N { +} +declare namespace N { +} +declare class C { + doSomething(): void; +} + +====================================================================== + +//// [/src/first/bin/first-output.d.ts] +interface TheFirst { + none: any; +} +declare const s = "Hello, world"; +interface NoJsForHereEither { + none: any; +} +declare function f(): string; +//# sourceMappingURL=first-output.d.ts.map + +//// [/src/first/bin/first-output.d.ts.map] +{"version":3,"file":"first-output.d.ts","sourceRoot":"","sources":["../first_PART1.ts","../first_part2.ts","../first_part3.ts"],"names":[],"mappings":"AAAA,UAAU,QAAQ;IACd,IAAI,EAAE,GAAG,CAAC;CACb;AAED,QAAA,MAAM,CAAC,iBAAiB,CAAC;AAEzB,UAAU,iBAAiB;IACvB,IAAI,EAAE,GAAG,CAAC;CACb;AERD,iBAAS,CAAC,WAET"} + +//// [/src/first/bin/first-output.js] +var s = "Hello, world"; +console.log(s); +console.log(f()); +function f() { + return "JS does hoists"; +} +//# sourceMappingURL=first-output.js.map + +//// [/src/first/bin/first-output.js.map] +{"version":3,"file":"first-output.js","sourceRoot":"","sources":["../first_PART1.ts","../first_part2.ts","../first_part3.ts"],"names":[],"mappings":"AAIA,IAAM,CAAC,GAAG,cAAc,CAAC;AAMzB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;ACVf,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;ACAjB,SAAS,CAAC;IACN,OAAO,gBAAgB,CAAC;AAC5B,CAAC"} + +//// [/src/first/bin/first-output.tsbuildinfo] +{ + "bundle": { + "commonSourceDirectory": "..", + "sourceFiles": [ + "../first_PART1.ts", + "../first_part2.ts", + "../first_part3.ts" + ], + "js": { + "sections": [ + { + "pos": 0, + "end": 110, + "kind": "text" + } + ] + }, + "dts": { + "sections": [ + { + "pos": 0, + "end": 157, + "kind": "text" + } + ] + } + }, + "version": "FakeTSVersion" +} + +//// [/src/first/bin/first-output.tsbuildinfo.baseline.txt] +====================================================================== +File:: /src/first/bin/first-output.js +---------------------------------------------------------------------- +text: (0-110) +var s = "Hello, world"; +console.log(s); +console.log(f()); +function f() { + return "JS does hoists"; +} + +====================================================================== +====================================================================== +File:: /src/first/bin/first-output.d.ts +---------------------------------------------------------------------- +text: (0-157) +interface TheFirst { + none: any; +} +declare const s = "Hello, world"; +interface NoJsForHereEither { + none: any; +} +declare function f(): string; + +====================================================================== + +//// [/src/third/thirdjs/output/third-output.d.ts] +interface TheFirst { + none: any; +} +declare const s = "Hello, world"; +interface NoJsForHereEither { + none: any; +} +declare function f(): string; +declare namespace N { +} +declare namespace N { +} +declare class C { + doSomething(): void; +} +declare var c: C; +//# sourceMappingURL=third-output.d.ts.map + +//// [/src/third/thirdjs/output/third-output.d.ts.map] +{"version":3,"file":"third-output.d.ts","sourceRoot":"","sources":["../../../first/first_PART1.ts","../../../first/first_part3.ts","../../../second/second_part1.ts","../../../second/second_part2.ts","../../third_part1.ts"],"names":[],"mappings":"AAAA,UAAU,QAAQ;IACd,IAAI,EAAE,GAAG,CAAC;CACb;AAED,QAAA,MAAM,CAAC,iBAAiB,CAAC;AAEzB,UAAU,iBAAiB;IACvB,IAAI,EAAE,GAAG,CAAC;CACb;ACRD,iBAAS,CAAC,WAET;ACFD,kBAAU,CAAC,CAAC;CAEX;AAED,kBAAU,CAAC,CAAC;CAMX;ACVD,cAAM,CAAC;IACH,WAAW;CAGd;ACJD,QAAA,IAAI,CAAC,GAAU,CAAC"} + +//// [/src/third/thirdjs/output/third-output.js] +var s = "Hello, world"; +console.log(s); +console.log(f()); +function f() { + return "JS does hoists"; +} +var N; +(function (N) { + function f() { + console.log('testing'); + } + f(); +})(N || (N = {})); +var C = (function () { + function C() { + } + C.prototype.doSomething = function () { + console.log("something got done"); + }; + return C; +}()); +var c = new C(); +c.doSomething(); +//# sourceMappingURL=third-output.js.map + +//// [/src/third/thirdjs/output/third-output.js.map] +{"version":3,"file":"third-output.js","sourceRoot":"","sources":["../../../first/first_PART1.ts","../../../first/first_part2.ts","../../../first/first_part3.ts","../../../second/second_part1.ts","../../../second/second_part2.ts","../../third_part1.ts"],"names":[],"mappings":"AAIA,IAAM,CAAC,GAAG,cAAc,CAAC;AAMzB,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC;ACVf,OAAO,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC,CAAC;ACAjB,SAAS,CAAC;IACN,OAAO,gBAAgB,CAAC;AAC5B,CAAC;ACED,IAAU,CAAC,CAMV;AAND,WAAU,CAAC;IACP,SAAS,CAAC;QACN,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;IAC3B,CAAC;IAED,CAAC,EAAE,CAAC;AACR,CAAC,EANS,CAAC,KAAD,CAAC,QAMV;ACVD;IAAA;IAIA,CAAC;IAHG,uBAAW,GAAX;QACI,OAAO,CAAC,GAAG,CAAC,oBAAoB,CAAC,CAAC;IACtC,CAAC;IACL,QAAC;AAAD,CAAC,AAJD,IAIC;ACJD,IAAI,CAAC,GAAG,IAAI,CAAC,EAAE,CAAC;AAChB,CAAC,CAAC,WAAW,EAAE,CAAC"} + +//// [/src/third/tsconfig.json] +{ + "compilerOptions": { + "target": "es5", + + "removeComments": true, + "strict": false, + "sourceMap": true, + "declarationMap": true, + "declaration": true, + "outFile": "./thirdjs/output/third-output.js", + "skipDefaultLibCheck": true + }, + "files": [ + "third_part1.ts" + ], + "references": [ + { "path": "../first", "prepend": true }, + { "path": "../second", "prepend": true }, + ] +} + + diff --git a/tests/baselines/reference/tsbuild/outFile/initial-build/verify-buildInfo-absence-results-in-new-build.js b/tests/baselines/reference/tsbuild/outFile/initial-build/verify-buildInfo-absence-results-in-new-build.js new file mode 100644 index 00000000000..310e56c01fb --- /dev/null +++ b/tests/baselines/reference/tsbuild/outFile/initial-build/verify-buildInfo-absence-results-in-new-build.js @@ -0,0 +1,129 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/third --verbose +12:00:00 AM - Projects in this build: + * src/first/tsconfig.json + * src/second/tsconfig.json + * src/third/tsconfig.json + +12:00:00 AM - Project 'src/first/tsconfig.json' is out of date because output file 'src/first/bin/first-output.tsbuildinfo' does not exist + +12:00:00 AM - Building project '/src/first/tsconfig.json'... + +12:00:00 AM - Project 'src/second/tsconfig.json' is up to date because newest input 'src/second/second_part1.ts' is older than oldest output 'src/2/second-output.js' + +12:00:00 AM - Project 'src/third/tsconfig.json' is out of date because output of its dependency 'src/first' has changed + +12:00:00 AM - Updating output of project '/src/third/tsconfig.json'... + +12:00:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/first/bin/first-output.d.ts] file written with same contents +//// [/src/first/bin/first-output.d.ts.map] file written with same contents +//// [/src/first/bin/first-output.js] file written with same contents +//// [/src/first/bin/first-output.js.map] file written with same contents +//// [/src/first/bin/first-output.tsbuildinfo] file written with same contents +//// [/src/first/bin/first-output.tsbuildinfo.baseline.txt] +====================================================================== +File:: /src/first/bin/first-output.js +---------------------------------------------------------------------- +text: (0-110) +var s = "Hello, world"; +console.log(s); +console.log(f()); +function f() { + return "JS does hoists"; +} + +====================================================================== +====================================================================== +File:: /src/first/bin/first-output.d.ts +---------------------------------------------------------------------- +text: (0-157) +interface TheFirst { + none: any; +} +declare const s = "Hello, world"; +interface NoJsForHereEither { + none: any; +} +declare function f(): string; + +====================================================================== + +//// [/src/third/thirdjs/output/third-output.tsbuildinfo] file written with same contents +//// [/src/third/thirdjs/output/third-output.tsbuildinfo.baseline.txt] +====================================================================== +File:: /src/third/thirdjs/output/third-output.js +---------------------------------------------------------------------- +prepend: (0-110):: ../../../first/bin/first-output.js texts:: 1 +>>-------------------------------------------------------------------- +text: (0-110) +var s = "Hello, world"; +console.log(s); +console.log(f()); +function f() { + return "JS does hoists"; +} + +---------------------------------------------------------------------- +prepend: (110-395):: ../../../2/second-output.js texts:: 1 +>>-------------------------------------------------------------------- +text: (110-395) +var N; +(function (N) { + function f() { + console.log('testing'); + } + f(); +})(N || (N = {})); +var C = (function () { + function C() { + } + C.prototype.doSomething = function () { + console.log("something got done"); + }; + return C; +}()); + +---------------------------------------------------------------------- +text: (395-431) +var c = new C(); +c.doSomething(); + +====================================================================== +====================================================================== +File:: /src/third/thirdjs/output/third-output.d.ts +---------------------------------------------------------------------- +prepend: (0-157):: ../../../first/bin/first-output.d.ts texts:: 1 +>>-------------------------------------------------------------------- +text: (0-157) +interface TheFirst { + none: any; +} +declare const s = "Hello, world"; +interface NoJsForHereEither { + none: any; +} +declare function f(): string; + +---------------------------------------------------------------------- +prepend: (157-257):: ../../../2/second-output.d.ts texts:: 1 +>>-------------------------------------------------------------------- +text: (157-257) +declare namespace N { +} +declare namespace N { +} +declare class C { + doSomething(): void; +} + +---------------------------------------------------------------------- +text: (257-276) +declare var c: C; + +====================================================================== + diff --git a/tests/baselines/reference/tsbuild/outFile/no-change-run/clean-projects.js b/tests/baselines/reference/tsbuild/outFile/no-change-run/clean-projects.js new file mode 100644 index 00000000000..e9007f59a9b --- /dev/null +++ b/tests/baselines/reference/tsbuild/outFile/no-change-run/clean-projects.js @@ -0,0 +1,5 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --b /src/third --clean +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/baseline-sectioned-sourcemaps.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/baseline-sectioned-sourcemaps.js index 136509b59b8..e5d4f35c93f 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/baseline-sectioned-sourcemaps.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/baseline-sectioned-sourcemaps.js @@ -15,7 +15,7 @@ 12:04:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/emitHelpers-in-all-projects.js index 605e02ffcc8..5b05d6cff8c 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/emitHelpers-in-all-projects.js @@ -15,7 +15,7 @@ 12:04:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/multiple-prologues-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/multiple-prologues-in-all-projects.js index a10f26edcc3..c8a9d53d874 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/multiple-prologues-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/multiple-prologues-in-all-projects.js @@ -15,7 +15,7 @@ 12:04:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/shebang-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/shebang-in-all-projects.js index 874c818de64..68482354748 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/shebang-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/shebang-in-all-projects.js @@ -15,7 +15,7 @@ 12:04:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/strict-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/strict-in-all-projects.js index 9d7471bf95c..009e53ddc3a 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/strict-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/strict-in-all-projects.js @@ -15,7 +15,7 @@ 12:04:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/stripInternal-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/stripInternal-when-one-two-three-are-prepended-in-order.js index cca89f269e9..2c15d3a563a 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/stripInternal-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/stripInternal-when-one-two-three-are-prepended-in-order.js @@ -17,7 +17,7 @@ 12:04:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/second/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/stripInternal.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/stripInternal.js index 397f586217e..a40c29ef70c 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/stripInternal.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/stripInternal.js @@ -15,7 +15,7 @@ 12:04:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/triple-slash-refs-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/triple-slash-refs-in-all-projects.js index 25cb88e8ddc..e8896f24c61 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/triple-slash-refs-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-changes/triple-slash-refs-in-all-projects.js @@ -15,7 +15,7 @@ 12:04:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/baseline-sectioned-sourcemaps.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/baseline-sectioned-sourcemaps.js index e0b14d9a65d..a805c14be90 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/baseline-sectioned-sourcemaps.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/baseline-sectioned-sourcemaps.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/emitHelpers-in-all-projects.js index cb0c5eb2bc6..f841221d940 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/emitHelpers-in-all-projects.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/emitHelpers-in-only-one-dependency-project.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/emitHelpers-in-only-one-dependency-project.js index 11497868243..c9238840812 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/emitHelpers-in-only-one-dependency-project.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/emitHelpers-in-only-one-dependency-project.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-emitHelpers-in-all-projects.js index d8e06c669bc..468e4b45ad6 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-emitHelpers-in-all-projects.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-emitHelpers-in-different-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-emitHelpers-in-different-projects.js index 692390e1645..838cd926887 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-emitHelpers-in-different-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-emitHelpers-in-different-projects.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-prologues-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-prologues-in-all-projects.js index 30075f17e26..6ed01121bcf 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-prologues-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-prologues-in-all-projects.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-prologues-in-different-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-prologues-in-different-projects.js index ba51e272d7e..8e36508f65b 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-prologues-in-different-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/multiple-prologues-in-different-projects.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/shebang-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/shebang-in-all-projects.js index bbddaba06ea..1a06d37841a 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/shebang-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/shebang-in-all-projects.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/shebang-in-only-one-dependency-project.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/shebang-in-only-one-dependency-project.js index 8cbabe3c880..38ad3648800 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/shebang-in-only-one-dependency-project.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/shebang-in-only-one-dependency-project.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/strict-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/strict-in-all-projects.js index a97bd2a2197..f5d6f6035f4 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/strict-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/strict-in-all-projects.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/strict-in-one-dependency.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/strict-in-one-dependency.js index 9bdfad323e9..b1068d14dd8 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/strict-in-one-dependency.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/strict-in-one-dependency.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js index ac11658e2ca..18b93f1463d 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js @@ -21,7 +21,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.js] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-comment.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-comment.js index 48790653874..23b7fc027ca 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-comment.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-comment.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js index 957ed1cd9b1..3f048c5515b 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js @@ -21,7 +21,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.js] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-with-comments-emit-enabled.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-with-comments-emit-enabled.js index beb8d35124e..c68c0d44e93 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-with-comments-emit-enabled.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-jsdoc-style-with-comments-emit-enabled.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-when-one-two-three-are-prepended-in-order.js index 512c530ffff..a5c99ef2c31 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-when-one-two-three-are-prepended-in-order.js @@ -21,7 +21,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/second/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js index 1eed13c8342..590b1a33f1a 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js @@ -21,7 +21,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.js] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-with-comments-emit-enabled.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-with-comments-emit-enabled.js index 51479fbc65d..7e73dc4308f 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-with-comments-emit-enabled.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal-with-comments-emit-enabled.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal.js index 4a70c73124e..e8947998db3 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/stripInternal.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/triple-slash-refs-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/triple-slash-refs-in-all-projects.js index b11dc0218e2..285c570630d 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/triple-slash-refs-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/triple-slash-refs-in-all-projects.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/triple-slash-refs-in-one-project.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/triple-slash-refs-in-one-project.js index 8d9f639e805..1beaaa4d915 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/triple-slash-refs-in-one-project.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/triple-slash-refs-in-one-project.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/when-final-project-is-not-composite-but-uses-project-references.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/when-final-project-is-not-composite-but-uses-project-references.js index 66e8fed0677..71052c4b610 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/when-final-project-is-not-composite-but-uses-project-references.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/when-final-project-is-not-composite-but-uses-project-references.js @@ -15,7 +15,7 @@ 12:04:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/when-source-files-are-empty-in-the-own-file.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/when-source-files-are-empty-in-the-own-file.js index c41ea2edc69..9df84107d04 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/when-source-files-are-empty-in-the-own-file.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-declaration-doesnt-change/when-source-files-are-empty-in-the-own-file.js @@ -17,7 +17,7 @@ 12:04:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/emitHelpers-in-all-projects.js index 971adc119ac..8a95a54f99a 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/emitHelpers-in-all-projects.js @@ -17,7 +17,7 @@ 12:12:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/emitHelpers-in-only-one-dependency-project.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/emitHelpers-in-only-one-dependency-project.js index 4224fc07853..aa9240a62a7 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/emitHelpers-in-only-one-dependency-project.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/emitHelpers-in-only-one-dependency-project.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-all-projects.js index 88807139890..d6dded28089 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-all-projects.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-different-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-different-projects.js index 2c4350cc261..2185893e4cb 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-different-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-emitHelpers-in-different-projects.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-prologues-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-prologues-in-all-projects.js index b7da2a1ff96..f1ed7eceec2 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-prologues-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-prologues-in-all-projects.js @@ -17,7 +17,7 @@ 12:12:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-prologues-in-different-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-prologues-in-different-projects.js index 7b9dc11ca9b..0813221bc46 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-prologues-in-different-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/multiple-prologues-in-different-projects.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/strict-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/strict-in-all-projects.js index f762fa7ac29..43be2024501 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/strict-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/strict-in-all-projects.js @@ -17,7 +17,7 @@ 12:12:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/strict-in-one-dependency.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/strict-in-one-dependency.js index 0e8a092a7d1..5742487e7bf 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/strict-in-one-dependency.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/strict-in-one-dependency.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js index d1aac8b70e8..87742bb7bdf 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js @@ -21,7 +21,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts.map] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-jsdoc-style-comment.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-jsdoc-style-comment.js index 44b2e3afe3f..dc7b21b3dea 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-jsdoc-style-comment.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-jsdoc-style-comment.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-when-one-two-three-are-prepended-in-order.js index 1fec0b7b22e..2862e36ee86 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-when-one-two-three-are-prepended-in-order.js @@ -21,7 +21,7 @@ 12:12:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/second/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js index 774cd39ea59..972fd46db7d 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js @@ -21,7 +21,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts.map] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-with-comments-emit-enabled.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-with-comments-emit-enabled.js index a4a3c13a5f4..99486e27c0a 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-with-comments-emit-enabled.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal-with-comments-emit-enabled.js @@ -17,7 +17,7 @@ 12:08:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/first/bin/first-output.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal.js b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal.js index a048c6ecd75..280f291e8ad 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/incremental-headers-change-without-dts-changes/stripInternal.js @@ -17,7 +17,7 @@ 12:12:00 AM - Updating unchanged output timestamps of project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/baseline-sectioned-sourcemaps.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/baseline-sectioned-sourcemaps.js index 2b217d8a1d1..bd3389dfbc3 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/baseline-sectioned-sourcemaps.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/baseline-sectioned-sourcemaps.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/declarationMap-and-sourceMap-disabled.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/declarationMap-and-sourceMap-disabled.js index 41e8f94b4aa..f5ade132423 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/declarationMap-and-sourceMap-disabled.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/declarationMap-and-sourceMap-disabled.js @@ -17,7 +17,7 @@ 12:00:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/emitHelpers-in-all-projects.js index 7dbec0f66cf..0aa82f67719 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/emitHelpers-in-all-projects.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/emitHelpers-in-only-one-dependency-project.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/emitHelpers-in-only-one-dependency-project.js index b946940addd..5418a2999e9 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/emitHelpers-in-only-one-dependency-project.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/emitHelpers-in-only-one-dependency-project.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-emitHelpers-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-emitHelpers-in-all-projects.js index 242690d2885..4f45dea3525 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-emitHelpers-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-emitHelpers-in-all-projects.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-emitHelpers-in-different-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-emitHelpers-in-different-projects.js index 93ba9fcc3e3..fa74878263c 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-emitHelpers-in-different-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-emitHelpers-in-different-projects.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-prologues-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-prologues-in-all-projects.js index 21f8943ae6b..3384786dff3 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-prologues-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-prologues-in-all-projects.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-prologues-in-different-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-prologues-in-different-projects.js index ea725d85d49..739026ac55a 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-prologues-in-different-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/multiple-prologues-in-different-projects.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/shebang-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/shebang-in-all-projects.js index b8adefd8976..dcf2a348406 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/shebang-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/shebang-in-all-projects.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/shebang-in-only-one-dependency-project.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/shebang-in-only-one-dependency-project.js index bab82334961..2544423aa9a 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/shebang-in-only-one-dependency-project.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/shebang-in-only-one-dependency-project.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/strict-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/strict-in-all-projects.js index 1471bdb3090..e09acc6c682 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/strict-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/strict-in-all-projects.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/strict-in-one-dependency.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/strict-in-one-dependency.js index 8a4cce33dfc..d959c28bc6b 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/strict-in-one-dependency.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/strict-in-one-dependency.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-baseline-when-internal-is-inside-another-internal.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-baseline-when-internal-is-inside-another-internal.js index 5595b32ed57..5c650827310 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-baseline-when-internal-is-inside-another-internal.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-baseline-when-internal-is-inside-another-internal.js @@ -17,7 +17,7 @@ 12:00:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js index 339374d5326..b6a9dac9f4b 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-comment-when-one-two-three-are-prepended-in-order.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-comment.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-comment.js index 329530576c0..34b42935b4f 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-comment.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-comment.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js index 27a636b0f7c..1d167197b09 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-with-comments-emit-enabled.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-with-comments-emit-enabled.js index ae47b924825..f55627f1e1f 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-with-comments-emit-enabled.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-jsdoc-style-with-comments-emit-enabled.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-few-members-of-enum-are-internal.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-few-members-of-enum-are-internal.js index 91cf996eddd..ac4b4506e9c 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-few-members-of-enum-are-internal.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-few-members-of-enum-are-internal.js @@ -17,7 +17,7 @@ 12:00:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-one-two-three-are-prepended-in-order.js index 360d2c392a2..33043052625 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-one-two-three-are-prepended-in-order.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/second/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-prepend-is-completely-internal.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-prepend-is-completely-internal.js new file mode 100644 index 00000000000..1acbd84075d --- /dev/null +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-when-prepend-is-completely-internal.js @@ -0,0 +1,310 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/third --verbose +12:00:00 AM - Projects in this build: + * src/first/tsconfig.json + * src/third/tsconfig.json + +12:00:00 AM - Project 'src/first/tsconfig.json' is out of date because output file 'src/first/bin/first-output.js' does not exist + +12:00:00 AM - Building project '/src/first/tsconfig.json'... + +12:00:00 AM - Project 'src/third/tsconfig.json' is out of date because output file 'src/third/thirdjs/output/third-output.js' does not exist + +12:00:00 AM - Building project '/src/third/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/first/bin/first-output.d.ts] +declare const A = 1; +//# sourceMappingURL=first-output.d.ts.map + +//// [/src/first/bin/first-output.d.ts.map] +{"version":3,"file":"first-output.d.ts","sourceRoot":"","sources":["../first_PART1.ts"],"names":[],"mappings":"AAAgB,QAAA,MAAM,CAAC,IAAI,CAAC"} + +//// [/src/first/bin/first-output.d.ts.map.baseline.txt] +=================================================================== +JsFile: first-output.d.ts +mapUrl: first-output.d.ts.map +sourceRoot: +sources: ../first_PART1.ts +=================================================================== +------------------------------------------------------------------- +emittedFile:/src/first/bin/first-output.d.ts +sourceFile:../first_PART1.ts +------------------------------------------------------------------- +>>>declare const A = 1; +1 > +2 >^^^^^^^^ +3 > ^^^^^^ +4 > ^ +5 > ^^^^ +6 > ^ +7 > ^^^^^^^^^^^^^^^^^^^^^-> +1 >/* @internal */ +2 > +3 > const +4 > A +5 > = 1 +6 > ; +1 >Emitted(1, 1) Source(1, 17) + SourceIndex(0) +2 >Emitted(1, 9) Source(1, 17) + SourceIndex(0) +3 >Emitted(1, 15) Source(1, 23) + SourceIndex(0) +4 >Emitted(1, 16) Source(1, 24) + SourceIndex(0) +5 >Emitted(1, 20) Source(1, 28) + SourceIndex(0) +6 >Emitted(1, 21) Source(1, 29) + SourceIndex(0) +--- +>>>//# sourceMappingURL=first-output.d.ts.map + +//// [/src/first/bin/first-output.js] +/* @internal */ var A = 1; +//# sourceMappingURL=first-output.js.map + +//// [/src/first/bin/first-output.js.map] +{"version":3,"file":"first-output.js","sourceRoot":"","sources":["../first_PART1.ts"],"names":[],"mappings":"AAAA,eAAe,CAAC,IAAM,CAAC,GAAG,CAAC,CAAC"} + +//// [/src/first/bin/first-output.js.map.baseline.txt] +=================================================================== +JsFile: first-output.js +mapUrl: first-output.js.map +sourceRoot: +sources: ../first_PART1.ts +=================================================================== +------------------------------------------------------------------- +emittedFile:/src/first/bin/first-output.js +sourceFile:../first_PART1.ts +------------------------------------------------------------------- +>>>/* @internal */ var A = 1; +1 > +2 >^^^^^^^^^^^^^^^ +3 > ^ +4 > ^^^^ +5 > ^ +6 > ^^^ +7 > ^ +8 > ^ +9 > ^^^^^^^^^^^^^-> +1 > +2 >/* @internal */ +3 > +4 > const +5 > A +6 > = +7 > 1 +8 > ; +1 >Emitted(1, 1) Source(1, 1) + SourceIndex(0) +2 >Emitted(1, 16) Source(1, 16) + SourceIndex(0) +3 >Emitted(1, 17) Source(1, 17) + SourceIndex(0) +4 >Emitted(1, 21) Source(1, 23) + SourceIndex(0) +5 >Emitted(1, 22) Source(1, 24) + SourceIndex(0) +6 >Emitted(1, 25) Source(1, 27) + SourceIndex(0) +7 >Emitted(1, 26) Source(1, 28) + SourceIndex(0) +8 >Emitted(1, 27) Source(1, 29) + SourceIndex(0) +--- +>>>//# sourceMappingURL=first-output.js.map + +//// [/src/first/bin/first-output.tsbuildinfo] +{ + "bundle": { + "commonSourceDirectory": "..", + "sourceFiles": [ + "../first_PART1.ts" + ], + "js": { + "sections": [ + { + "pos": 0, + "end": 28, + "kind": "text" + } + ] + }, + "dts": { + "sections": [ + { + "pos": 0, + "end": 20, + "kind": "internal" + } + ] + } + }, + "version": "FakeTSVersion" +} + +//// [/src/first/bin/first-output.tsbuildinfo.baseline.txt] +====================================================================== +File:: /src/first/bin/first-output.js +---------------------------------------------------------------------- +text: (0-28) +/* @internal */ var A = 1; + +====================================================================== +====================================================================== +File:: /src/first/bin/first-output.d.ts +---------------------------------------------------------------------- +internal: (0-20) +declare const A = 1; +====================================================================== + +//// [/src/first/first_PART1.ts] +/* @internal */ const A = 1; + +//// [/src/first/tsconfig.json] +{"compilerOptions":{"composite":true,"declaration":true,"declarationMap":true,"skipDefaultLibCheck":true,"sourceMap":true,"outFile":"./bin/first-output.js"},"files":["/src/first/first_PART1.ts"]} + +//// [/src/third/thirdjs/output/third-output.d.ts] +declare const B = 2; + + +//// [/src/third/thirdjs/output/third-output.js] +/* @internal */ var A = 1; +var B = 2; +//# sourceMappingURL=third-output.js.map + +//// [/src/third/thirdjs/output/third-output.js.map] +{"version":3,"file":"third-output.js","sourceRoot":"","sources":["../../../first/first_PART1.ts","../../third_part1.ts"],"names":[],"mappings":"AAAA,eAAe,CAAC,IAAM,CAAC,GAAG,CAAC,CAAC;ACA5B,IAAM,CAAC,GAAG,CAAC,CAAC"} + +//// [/src/third/thirdjs/output/third-output.js.map.baseline.txt] +=================================================================== +JsFile: third-output.js +mapUrl: third-output.js.map +sourceRoot: +sources: ../../../first/first_PART1.ts,../../third_part1.ts +=================================================================== +------------------------------------------------------------------- +emittedFile:/src/third/thirdjs/output/third-output.js +sourceFile:../../../first/first_PART1.ts +------------------------------------------------------------------- +>>>/* @internal */ var A = 1; +1 > +2 >^^^^^^^^^^^^^^^ +3 > ^ +4 > ^^^^ +5 > ^ +6 > ^^^ +7 > ^ +8 > ^ +1 > +2 >/* @internal */ +3 > +4 > const +5 > A +6 > = +7 > 1 +8 > ; +1 >Emitted(1, 1) Source(1, 1) + SourceIndex(0) +2 >Emitted(1, 16) Source(1, 16) + SourceIndex(0) +3 >Emitted(1, 17) Source(1, 17) + SourceIndex(0) +4 >Emitted(1, 21) Source(1, 23) + SourceIndex(0) +5 >Emitted(1, 22) Source(1, 24) + SourceIndex(0) +6 >Emitted(1, 25) Source(1, 27) + SourceIndex(0) +7 >Emitted(1, 26) Source(1, 28) + SourceIndex(0) +8 >Emitted(1, 27) Source(1, 29) + SourceIndex(0) +--- +------------------------------------------------------------------- +emittedFile:/src/third/thirdjs/output/third-output.js +sourceFile:../../third_part1.ts +------------------------------------------------------------------- +>>>var B = 2; +1 > +2 >^^^^ +3 > ^ +4 > ^^^ +5 > ^ +6 > ^ +7 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^-> +1 > +2 >const +3 > B +4 > = +5 > 2 +6 > ; +1 >Emitted(2, 1) Source(1, 1) + SourceIndex(1) +2 >Emitted(2, 5) Source(1, 7) + SourceIndex(1) +3 >Emitted(2, 6) Source(1, 8) + SourceIndex(1) +4 >Emitted(2, 9) Source(1, 11) + SourceIndex(1) +5 >Emitted(2, 10) Source(1, 12) + SourceIndex(1) +6 >Emitted(2, 11) Source(1, 13) + SourceIndex(1) +--- +>>>//# sourceMappingURL=third-output.js.map + +//// [/src/third/thirdjs/output/third-output.tsbuildinfo] +{ + "bundle": { + "commonSourceDirectory": "../..", + "sourceFiles": [ + "../../third_part1.ts" + ], + "js": { + "sections": [ + { + "pos": 0, + "end": 28, + "kind": "prepend", + "data": "../../../first/bin/first-output.js", + "texts": [ + { + "pos": 0, + "end": 28, + "kind": "text" + } + ] + }, + { + "pos": 28, + "end": 40, + "kind": "text" + } + ] + }, + "dts": { + "sections": [ + { + "pos": 0, + "end": 0, + "kind": "prepend", + "data": "../../../first/bin/first-output.d.ts", + "texts": [] + }, + { + "pos": 0, + "end": 22, + "kind": "text" + } + ] + } + }, + "version": "FakeTSVersion" +} + +//// [/src/third/thirdjs/output/third-output.tsbuildinfo.baseline.txt] +====================================================================== +File:: /src/third/thirdjs/output/third-output.js +---------------------------------------------------------------------- +prepend: (0-28):: ../../../first/bin/first-output.js texts:: 1 +>>-------------------------------------------------------------------- +text: (0-28) +/* @internal */ var A = 1; + +---------------------------------------------------------------------- +text: (28-40) +var B = 2; + +====================================================================== +====================================================================== +File:: /src/third/thirdjs/output/third-output.d.ts +---------------------------------------------------------------------- +prepend: (0-0):: ../../../first/bin/first-output.d.ts texts:: 0 +---------------------------------------------------------------------- +text: (0-22) +declare const B = 2; + +====================================================================== + +//// [/src/third/third_part1.ts] +const B = 2; + +//// [/src/third/tsconfig.json] +{"compilerOptions":{"composite":true,"declaration":true,"declarationMap":false,"stripInternal":true,"sourceMap":true,"outFile":"./thirdjs/output/third-output.js"},"references":[{"path":"../first","prepend":true}],"files":["/src/third/third_part1.ts"]} + diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js index b9106767cea..fb179a1c7a3 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-with-comments-emit-enabled-when-one-two-three-are-prepended-in-order.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-with-comments-emit-enabled.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-with-comments-emit-enabled.js index 80e0f71cc55..e6ce5a30667 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-with-comments-emit-enabled.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal-with-comments-emit-enabled.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal.js index 467077d6a66..064e40bdfc9 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/stripInternal.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/triple-slash-refs-in-all-projects.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/triple-slash-refs-in-all-projects.js index c8efbd205e6..c0f287ba863 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/triple-slash-refs-in-all-projects.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/triple-slash-refs-in-all-projects.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/third/tsconfig.json": 1, "/src/first/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/triple-slash-refs-in-one-project.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/triple-slash-refs-in-one-project.js index 471309f35f0..d2396185240 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/triple-slash-refs-in-one-project.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/triple-slash-refs-in-one-project.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-is-not-composite-but-incremental.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-is-not-composite-but-incremental.js index 81bec95d4f6..3072958e47c 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-is-not-composite-but-incremental.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-is-not-composite-but-incremental.js @@ -17,7 +17,7 @@ 12:00:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-is-not-composite-but-uses-project-references.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-is-not-composite-but-uses-project-references.js index 2e7b1f1663f..936365084f5 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-is-not-composite-but-uses-project-references.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-is-not-composite-but-uses-project-references.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-specifies-tsBuildInfoFile.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-specifies-tsBuildInfoFile.js index b0131b6af56..67d83cd6365 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-specifies-tsBuildInfoFile.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-final-project-specifies-tsBuildInfoFile.js @@ -17,7 +17,7 @@ 12:00:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-source-files-are-empty-in-the-own-file.js b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-source-files-are-empty-in-the-own-file.js index deb7dbd86e6..40ff6cf19a1 100644 --- a/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-source-files-are-empty-in-the-own-file.js +++ b/tests/baselines/reference/tsbuild/outfile-concat/initial-build/when-source-files-are-empty-in-the-own-file.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/third/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/2/second-output.d.ts] diff --git a/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/builds-correctly.js b/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/builds-correctly.js new file mode 100644 index 00000000000..be599e64928 --- /dev/null +++ b/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/builds-correctly.js @@ -0,0 +1,107 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/src/main /src/src/other +exitCode:: ExitStatus.Success + + +//// [/src/dist/main/a.d.ts] +export {}; + + +//// [/src/dist/main/a.js] +"use strict"; +exports.__esModule = true; +var b_1 = require("./b"); +var a = b_1.b; + + +//// [/src/dist/main/b.d.ts] +export declare const b = 0; + + +//// [/src/dist/main/b.js] +"use strict"; +exports.__esModule = true; +exports.b = 0; + + +//// [/src/dist/main/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../../src/main/b.ts": { + "version": "-11678562673-export const b = 0;\r\n", + "signature": "-3829176033-export declare const b = 0;\r\n" + }, + "../../src/main/a.ts": { + "version": "-17071184049-import { b } from './b';\r\nconst a = b;", + "signature": "-4882119183-export {};\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "rootDir": "../../src", + "outDir": "..", + "skipDefaultLibCheck": true, + "configFilePath": "../../src/main/tsconfig.json" + }, + "referencedMap": { + "../../src/main/a.ts": [ + "../../src/main/b.ts" + ] + }, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../../lib/lib.d.ts", + "../../src/main/a.ts", + "../../src/main/b.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/dist/other/other.d.ts] +export declare const Other = 0; + + +//// [/src/dist/other/other.js] +"use strict"; +exports.__esModule = true; +exports.Other = 0; + + +//// [/src/dist/other/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../../src/other/other.ts": { + "version": "-2951227185-export const Other = 0;\r\n", + "signature": "-7996259489-export declare const Other = 0;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "rootDir": "../../src", + "outDir": "..", + "skipDefaultLibCheck": true, + "configFilePath": "../../src/other/tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../../lib/lib.d.ts", + "../../src/other/other.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/reports-error-for-same-tsbuildinfo-file-because-no-rootDir-in-the-base.js b/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/reports-error-for-same-tsbuildinfo-file-because-no-rootDir-in-the-base.js new file mode 100644 index 00000000000..1d5819876c4 --- /dev/null +++ b/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/reports-error-for-same-tsbuildinfo-file-because-no-rootDir-in-the-base.js @@ -0,0 +1,72 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/src/main --verbose +12:00:00 AM - Projects in this build: + * src/src/other/tsconfig.json + * src/src/main/tsconfig.json + +12:00:00 AM - Project 'src/src/other/tsconfig.json' is out of date because output file 'src/dist/other.js' does not exist + +12:00:00 AM - Building project '/src/src/other/tsconfig.json'... + +12:00:00 AM - Project 'src/src/main/tsconfig.json' is out of date because output file 'src/dist/a.js' does not exist + +12:00:00 AM - Building project '/src/src/main/tsconfig.json'... + +src/src/main/tsconfig.json(4,5): error TS6377: Cannot write file '/src/dist/tsconfig.tsbuildinfo' because it will overwrite '.tsbuildinfo' file generated by referenced project '/src/src/other' +exitCode:: ExitStatus.DiagnosticsPresent_OutputsGenerated + + +//// [/src/dist/other.d.ts] +export declare const Other = 0; + + +//// [/src/dist/other.js] +"use strict"; +exports.__esModule = true; +exports.Other = 0; + + +//// [/src/dist/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../src/other/other.ts": { + "version": "-2951227185-export const Other = 0;\r\n", + "signature": "-7996259489-export declare const Other = 0;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "outDir": "./", + "skipDefaultLibCheck": true, + "configFilePath": "../src/other/tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../src/other/other.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tsconfig.base.json] +{ + "compilerOptions": { + "composite": true, + "declaration": true, + + "outDir": "./dist/", + "skipDefaultLibCheck": true + }, + "exclude": [ + "node_modules" + ] +} + diff --git a/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/reports-error-for-same-tsbuildinfo-file.js b/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/reports-error-for-same-tsbuildinfo-file.js new file mode 100644 index 00000000000..0b821f41887 --- /dev/null +++ b/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/reports-error-for-same-tsbuildinfo-file.js @@ -0,0 +1,62 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/src/main --verbose +12:00:00 AM - Projects in this build: + * src/src/other/tsconfig.json + * src/src/main/tsconfig.json + +12:00:00 AM - Project 'src/src/other/tsconfig.json' is out of date because output file 'src/dist/other.js' does not exist + +12:00:00 AM - Building project '/src/src/other/tsconfig.json'... + +12:00:00 AM - Project 'src/src/main/tsconfig.json' is out of date because output file 'src/dist/a.js' does not exist + +12:00:00 AM - Building project '/src/src/main/tsconfig.json'... + +src/src/main/tsconfig.json(1,76): error TS6377: Cannot write file '/src/dist/tsconfig.tsbuildinfo' because it will overwrite '.tsbuildinfo' file generated by referenced project '/src/src/other' +exitCode:: ExitStatus.DiagnosticsPresent_OutputsGenerated + + +//// [/src/dist/other.d.ts] +export declare const Other = 0; + + +//// [/src/dist/other.js] +"use strict"; +exports.__esModule = true; +exports.Other = 0; + + +//// [/src/dist/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../src/other/other.ts": { + "version": "-2951227185-export const Other = 0;\r\n", + "signature": "-7996259489-export declare const Other = 0;\r\n" + } + }, + "options": { + "composite": true, + "outDir": "./", + "configFilePath": "../src/other/tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../src/other/other.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/src/main/tsconfig.json] +{"compilerOptions":{"composite":true,"outDir":"../../dist/"},"references":[{"path":"../other"}]} + +//// [/src/src/other/tsconfig.json] +{"compilerOptions":{"composite":true,"outDir":"../../dist/"}} + diff --git a/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/reports-no-error-when-tsbuildinfo-differ.js b/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/reports-no-error-when-tsbuildinfo-differ.js new file mode 100644 index 00000000000..7611491ff6a --- /dev/null +++ b/tests/baselines/reference/tsbuild/projectReferenceWithRootDirInParent/initial-build/reports-no-error-when-tsbuildinfo-differ.js @@ -0,0 +1,121 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/src/main/tsconfig.main.json --verbose +12:00:00 AM - Projects in this build: + * src/src/other/tsconfig.other.json + * src/src/main/tsconfig.main.json + +12:00:00 AM - Project 'src/src/other/tsconfig.other.json' is out of date because output file 'src/dist/other.js' does not exist + +12:00:00 AM - Building project '/src/src/other/tsconfig.other.json'... + +12:00:00 AM - Project 'src/src/main/tsconfig.main.json' is out of date because output file 'src/dist/a.js' does not exist + +12:00:00 AM - Building project '/src/src/main/tsconfig.main.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/dist/a.d.ts] +export {}; + + +//// [/src/dist/a.js] +"use strict"; +exports.__esModule = true; +var b_1 = require("./b"); +var a = b_1.b; + + +//// [/src/dist/b.d.ts] +export declare const b = 0; + + +//// [/src/dist/b.js] +"use strict"; +exports.__esModule = true; +exports.b = 0; + + +//// [/src/dist/other.d.ts] +export declare const Other = 0; + + +//// [/src/dist/other.js] +"use strict"; +exports.__esModule = true; +exports.Other = 0; + + +//// [/src/dist/tsconfig.main.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../src/main/b.ts": { + "version": "-11678562673-export const b = 0;\r\n", + "signature": "-3829176033-export declare const b = 0;\r\n" + }, + "../src/main/a.ts": { + "version": "-17071184049-import { b } from './b';\r\nconst a = b;", + "signature": "-4882119183-export {};\r\n" + } + }, + "options": { + "composite": true, + "outDir": "./", + "configFilePath": "../src/main/tsconfig.main.json" + }, + "referencedMap": { + "../src/main/a.ts": [ + "../src/main/b.ts" + ] + }, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../src/main/a.ts", + "../src/main/b.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/dist/tsconfig.other.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../src/other/other.ts": { + "version": "-2951227185-export const Other = 0;\r\n", + "signature": "-7996259489-export declare const Other = 0;\r\n" + } + }, + "options": { + "composite": true, + "outDir": "./", + "configFilePath": "../src/other/tsconfig.other.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../src/other/other.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/src/main/tsconfig.json] unlink +//// [/src/src/main/tsconfig.main.json] +{"compilerOptions":{"composite":true,"outDir":"../../dist/"},"references":[{"path":"../other/tsconfig.other.json"}]} + +//// [/src/src/other/tsconfig.json] unlink +//// [/src/src/other/tsconfig.other.json] +{"compilerOptions":{"composite":true,"outDir":"../../dist/"}} + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/files-containing-json-file.js b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/files-containing-json-file.js new file mode 100644 index 00000000000..1d953745219 --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/files-containing-json-file.js @@ -0,0 +1,73 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig_withFiles.json +exitCode:: ExitStatus.Success + + +//// [/src/dist/src/hello.d.ts] +export declare const hello: string; + + +//// [/src/dist/src/hello.json] +{ + "hello": "world" +} + + +//// [/src/dist/src/index.d.ts] +declare const _default: string; +export default _default; + + +//// [/src/dist/src/index.js] +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +exports.__esModule = true; +var hello_json_1 = __importDefault(require("./hello.json")); +exports["default"] = hello_json_1["default"].hello; + + +//// [/src/dist/tsconfig_withFiles.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../src/hello.json": { + "version": "6651571919-{\n \"hello\": \"world\"\n}", + "signature": "-4341462827-export declare const hello: string;\r\n" + }, + "../src/index.ts": { + "version": "-27703454282-import hello from \"./hello.json\"\n\nexport default hello.hello", + "signature": "-1680156224-declare const _default: string;\r\nexport default _default;\r\n" + } + }, + "options": { + "composite": true, + "moduleResolution": 2, + "module": 1, + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "outDir": "./", + "skipDefaultLibCheck": true, + "configFilePath": "../tsconfig_withFiles.json" + }, + "referencedMap": { + "../src/index.ts": [ + "../src/hello.json" + ] + }, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../src/hello.json", + "../src/index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/importing-json-module-from-project-reference.js b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/importing-json-module-from-project-reference.js new file mode 100644 index 00000000000..12542f55749 --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/importing-json-module-from-project-reference.js @@ -0,0 +1,108 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b src/tsconfig.json --verbose +12:01:00 AM - Projects in this build: + * src/strings/tsconfig.json + * src/main/tsconfig.json + * src/tsconfig.json + +12:01:00 AM - Project 'src/strings/tsconfig.json' is out of date because output file 'src/strings/tsconfig.tsbuildinfo' does not exist + +12:01:00 AM - Building project '/src/strings/tsconfig.json'... + +12:01:00 AM - Project 'src/main/tsconfig.json' is out of date because output file 'src/main/index.js' does not exist + +12:01:00 AM - Building project '/src/main/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/main/index.d.ts] +export {}; + + +//// [/src/main/index.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +var foo_json_1 = require("../strings/foo.json"); +console.log(foo_json_1.foo); + + +//// [/src/main/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../strings/foo.json": { + "version": "-1457151099-export declare const foo: string;\r\n", + "signature": "-1457151099-export declare const foo: string;\r\n" + }, + "./index.ts": { + "version": "-4651661680-import { foo } from '../strings/foo.json';\n\nconsole.log(foo);", + "signature": "-4882119183-export {};\r\n" + } + }, + "options": { + "target": 1, + "module": 1, + "rootDir": "..", + "composite": true, + "resolveJsonModule": true, + "strict": true, + "esModuleInterop": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "./index.ts": [ + "../strings/foo.d.ts" + ] + }, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../strings/foo.json", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/strings/foo.d.ts] +export declare const foo: string; + + +//// [/src/strings/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./foo.json": { + "version": "4395333385-{\n \"foo\": \"bar baz\"\n}", + "signature": "-1457151099-export declare const foo: string;\r\n" + } + }, + "options": { + "target": 1, + "module": 1, + "rootDir": "..", + "composite": true, + "resolveJsonModule": true, + "strict": true, + "esModuleInterop": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./foo.json" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-and-files.js b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-and-files.js new file mode 100644 index 00000000000..b4404190e27 --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-and-files.js @@ -0,0 +1,73 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig_withIncludeAndFiles.json +exitCode:: ExitStatus.Success + + +//// [/src/dist/src/hello.d.ts] +export declare const hello: string; + + +//// [/src/dist/src/hello.json] +{ + "hello": "world" +} + + +//// [/src/dist/src/index.d.ts] +declare const _default: string; +export default _default; + + +//// [/src/dist/src/index.js] +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +exports.__esModule = true; +var hello_json_1 = __importDefault(require("./hello.json")); +exports["default"] = hello_json_1["default"].hello; + + +//// [/src/dist/tsconfig_withIncludeAndFiles.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../src/hello.json": { + "version": "6651571919-{\n \"hello\": \"world\"\n}", + "signature": "-4341462827-export declare const hello: string;\r\n" + }, + "../src/index.ts": { + "version": "-27703454282-import hello from \"./hello.json\"\n\nexport default hello.hello", + "signature": "-1680156224-declare const _default: string;\r\nexport default _default;\r\n" + } + }, + "options": { + "composite": true, + "moduleResolution": 2, + "module": 1, + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "outDir": "./", + "skipDefaultLibCheck": true, + "configFilePath": "../tsconfig_withIncludeAndFiles.json" + }, + "referencedMap": { + "../src/index.ts": [ + "../src/hello.json" + ] + }, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../src/hello.json", + "../src/index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-of-json-along-with-other-include-and-file-name-matches-ts-file.js b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-of-json-along-with-other-include-and-file-name-matches-ts-file.js new file mode 100644 index 00000000000..0b516b4944f --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-of-json-along-with-other-include-and-file-name-matches-ts-file.js @@ -0,0 +1,15 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig_withIncludeOfJson.json +error TS5056: Cannot write file '/src/dist/src/index.d.ts' because it would be overwritten by multiple input files. +exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped + + +//// [/src/src/hello.json] unlink +//// [/src/src/index.json] +{"hello":"world"} + +//// [/src/src/index.ts] +import hello from "./index.json" + +export default hello.hello + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-of-json-along-with-other-include.js b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-of-json-along-with-other-include.js new file mode 100644 index 00000000000..5bedb91c4be --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-of-json-along-with-other-include.js @@ -0,0 +1,73 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig_withIncludeOfJson.json +exitCode:: ExitStatus.Success + + +//// [/src/dist/src/hello.d.ts] +export declare const hello: string; + + +//// [/src/dist/src/hello.json] +{ + "hello": "world" +} + + +//// [/src/dist/src/index.d.ts] +declare const _default: string; +export default _default; + + +//// [/src/dist/src/index.js] +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +exports.__esModule = true; +var hello_json_1 = __importDefault(require("./hello.json")); +exports["default"] = hello_json_1["default"].hello; + + +//// [/src/dist/tsconfig_withIncludeOfJson.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../src/hello.json": { + "version": "6651571919-{\n \"hello\": \"world\"\n}", + "signature": "-4341462827-export declare const hello: string;\r\n" + }, + "../src/index.ts": { + "version": "-27703454282-import hello from \"./hello.json\"\n\nexport default hello.hello", + "signature": "-1680156224-declare const _default: string;\r\nexport default _default;\r\n" + } + }, + "options": { + "composite": true, + "moduleResolution": 2, + "module": 1, + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "outDir": "./", + "skipDefaultLibCheck": true, + "configFilePath": "../tsconfig_withIncludeOfJson.json" + }, + "referencedMap": { + "../src/index.ts": [ + "../src/hello.json" + ] + }, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../src/hello.json", + "../src/index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-only.js b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-only.js new file mode 100644 index 00000000000..a809be90609 --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/include-only.js @@ -0,0 +1,6 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig_withInclude.json +src/src/index.ts(1,19): error TS6307: File '/src/src/hello.json' is not listed within the file list of project '/src/tsconfig_withInclude.json'. Projects must list all files or use an 'include' pattern. +exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped + + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/sourcemap.js b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/sourcemap.js new file mode 100644 index 00000000000..92ff87ebcad --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/sourcemap.js @@ -0,0 +1,101 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b src/tsconfig_withFiles.json --verbose +12:01:00 AM - Projects in this build: + * src/tsconfig_withFiles.json + +12:01:00 AM - Project 'src/tsconfig_withFiles.json' is out of date because output file 'src/dist/src/index.js' does not exist + +12:01:00 AM - Building project '/src/tsconfig_withFiles.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/dist/src/hello.d.ts] +export declare const hello: string; + + +//// [/src/dist/src/hello.json] +{ + "hello": "world" +} + + +//// [/src/dist/src/index.d.ts] +declare const _default: string; +export default _default; + + +//// [/src/dist/src/index.js] +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +exports.__esModule = true; +var hello_json_1 = __importDefault(require("./hello.json")); +exports["default"] = hello_json_1["default"].hello; +//# sourceMappingURL=index.js.map + +//// [/src/dist/src/index.js.map] +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";;;;;AAAA,4DAAgC;AAEhC,qBAAe,uBAAK,CAAC,KAAK,CAAA"} + +//// [/src/dist/tsconfig_withFiles.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../src/hello.json": { + "version": "6651571919-{\n \"hello\": \"world\"\n}", + "signature": "-4341462827-export declare const hello: string;\r\n" + }, + "../src/index.ts": { + "version": "-27703454282-import hello from \"./hello.json\"\n\nexport default hello.hello", + "signature": "-1680156224-declare const _default: string;\r\nexport default _default;\r\n" + } + }, + "options": { + "composite": true, + "sourceMap": true, + "moduleResolution": 2, + "module": 1, + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "outDir": "./", + "skipDefaultLibCheck": true, + "configFilePath": "../tsconfig_withFiles.json" + }, + "referencedMap": { + "../src/index.ts": [ + "../src/hello.json" + ] + }, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../src/hello.json", + "../src/index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tsconfig_withFiles.json] +{ + "compilerOptions": { + "composite": true, "sourceMap": true, + "moduleResolution": "node", + "module": "commonjs", + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "outDir": "dist", + "skipDefaultLibCheck": true + }, + "files": [ + "src/index.ts", "src/hello.json" + ] +} + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/without-outDir.js b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/without-outDir.js new file mode 100644 index 00000000000..b8756d8bf4b --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/initial-build/without-outDir.js @@ -0,0 +1,90 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b src/tsconfig_withFiles.json --verbose +12:01:00 AM - Projects in this build: + * src/tsconfig_withFiles.json + +12:01:00 AM - Project 'src/tsconfig_withFiles.json' is out of date because output file 'src/src/index.js' does not exist + +12:01:00 AM - Building project '/src/tsconfig_withFiles.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/src/hello.d.ts] +export declare const hello: string; + + +//// [/src/src/index.d.ts] +declare const _default: string; +export default _default; + + +//// [/src/src/index.js] +"use strict"; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +exports.__esModule = true; +var hello_json_1 = __importDefault(require("./hello.json")); +exports["default"] = hello_json_1["default"].hello; + + +//// [/src/tsconfig_withFiles.json] +{ + "compilerOptions": { + "composite": true, + "moduleResolution": "node", + "module": "commonjs", + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + + "skipDefaultLibCheck": true + }, + "files": [ + "src/index.ts", "src/hello.json" + ] +} + +//// [/src/tsconfig_withFiles.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./src/hello.json": { + "version": "6651571919-{\n \"hello\": \"world\"\n}", + "signature": "-4341462827-export declare const hello: string;\r\n" + }, + "./src/index.ts": { + "version": "-27703454282-import hello from \"./hello.json\"\n\nexport default hello.hello", + "signature": "-1680156224-declare const _default: string;\r\nexport default _default;\r\n" + } + }, + "options": { + "composite": true, + "moduleResolution": 2, + "module": 1, + "resolveJsonModule": true, + "esModuleInterop": true, + "allowSyntheticDefaultImports": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig_withFiles.json" + }, + "referencedMap": { + "./src/index.ts": [ + "./src/hello.json" + ] + }, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../lib/lib.d.ts", + "./src/hello.json", + "./src/index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/no-change-run/importing-json-module-from-project-reference.js b/tests/baselines/reference/tsbuild/resolveJsonModule/no-change-run/importing-json-module-from-project-reference.js new file mode 100644 index 00000000000..512a0f0e4a9 --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/no-change-run/importing-json-module-from-project-reference.js @@ -0,0 +1,14 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --b src/tsconfig.json --verbose +12:04:00 AM - Projects in this build: + * src/strings/tsconfig.json + * src/main/tsconfig.json + * src/tsconfig.json + +12:04:00 AM - Project 'src/strings/tsconfig.json' is up to date because newest input 'src/strings/foo.json' is older than oldest output 'src/strings/tsconfig.tsbuildinfo' + +12:04:00 AM - Project 'src/main/tsconfig.json' is up to date because newest input 'src/main/index.ts' is older than oldest output 'src/main/index.js' + +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/no-change-run/sourcemap.js b/tests/baselines/reference/tsbuild/resolveJsonModule/no-change-run/sourcemap.js new file mode 100644 index 00000000000..a5638600708 --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/no-change-run/sourcemap.js @@ -0,0 +1,10 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --b src/tsconfig_withFiles.json --verbose +12:04:00 AM - Projects in this build: + * src/tsconfig_withFiles.json + +12:04:00 AM - Project 'src/tsconfig_withFiles.json' is up to date because newest input 'src/src/index.ts' is older than oldest output 'src/dist/src/index.js' + +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsbuild/resolveJsonModule/no-change-run/without-outDir.js b/tests/baselines/reference/tsbuild/resolveJsonModule/no-change-run/without-outDir.js new file mode 100644 index 00000000000..a6329e50745 --- /dev/null +++ b/tests/baselines/reference/tsbuild/resolveJsonModule/no-change-run/without-outDir.js @@ -0,0 +1,10 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --b src/tsconfig_withFiles.json --verbose +12:04:00 AM - Projects in this build: + * src/tsconfig_withFiles.json + +12:04:00 AM - Project 'src/tsconfig_withFiles.json' is up to date because newest input 'src/src/index.ts' is older than oldest output 'src/src/index.js' + +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/Detects-type-only-changes-in-upstream-projects.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/Detects-type-only-changes-in-upstream-projects.js new file mode 100644 index 00000000000..7a6fd10afad --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/Detects-type-only-changes-in-upstream-projects.js @@ -0,0 +1,84 @@ +//// [/lib/incremental-declaration-changesOutput.txt] +/lib/tsc --b /src/tests --verbose +12:08:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/logic/tsconfig.json + * src/tests/tsconfig.json + +12:08:00 AM - Project 'src/core/tsconfig.json' is out of date because oldest output 'src/core/anotherModule.js' is older than newest input 'src/core/index.ts' + +12:08:00 AM - Building project '/src/core/tsconfig.json'... + +12:08:00 AM - Updating unchanged output timestamps of project '/src/core/tsconfig.json'... + +12:08:00 AM - Project 'src/logic/tsconfig.json' is up to date with .d.ts files from its dependencies + +12:08:00 AM - Updating output timestamps of project '/src/logic/tsconfig.json'... + +12:08:00 AM - Project 'src/tests/tsconfig.json' is up to date with .d.ts files from its dependencies + +12:08:00 AM - Updating output timestamps of project '/src/tests/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/core/index.d.ts] file written with same contents +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,EAAE,MAAyB,CAAC;AACnD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB;AAC/D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +exports.someString = "WELCOME PLANET"; +function leftPad(s, n) { return s + n; } +exports.leftPad = leftPad; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/index.ts] +export const someString: string = "WELCOME PLANET"; +export function leftPad(s: string, n: number) { return s + n; } +export function multiply(a: number, b: number) { return a * b; } + + +//// [/src/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./anothermodule.ts": { + "version": "-2676574883-export const World = \"hello\";\r\n", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-2157245566-export const someString: string = \"WELCOME PLANET\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "./some_decl.d.ts": { + "version": "-9253692965-declare const dts: any;\r\n", + "signature": "-9253692965-declare const dts: any;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./anothermodule.ts", + "./index.ts", + "./some_decl.d.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/rebuilds-from-start-if-force-option-is-set.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/rebuilds-from-start-if-force-option-is-set.js new file mode 100644 index 00000000000..1d1428887aa --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/rebuilds-from-start-if-force-option-is-set.js @@ -0,0 +1,36 @@ +//// [/lib/incremental-declaration-changesOutput.txt] +/lib/tsc --b /src/tests --verbose --force +12:16:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/logic/tsconfig.json + * src/tests/tsconfig.json + +12:16:00 AM - Project 'src/core/tsconfig.json' is up to date because newest input 'src/core/anotherModule.ts' is older than oldest output 'src/core/anotherModule.js' + +12:16:00 AM - Building project '/src/core/tsconfig.json'... + +12:16:00 AM - Project 'src/logic/tsconfig.json' is up to date with .d.ts files from its dependencies + +12:16:00 AM - Building project '/src/logic/tsconfig.json'... + +12:16:00 AM - Project 'src/tests/tsconfig.json' is up to date with .d.ts files from its dependencies + +12:16:00 AM - Building project '/src/tests/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] file written with same contents +//// [/src/core/anotherModule.d.ts.map] file written with same contents +//// [/src/core/anotherModule.js] file written with same contents +//// [/src/core/index.d.ts] file written with same contents +//// [/src/core/index.d.ts.map] file written with same contents +//// [/src/core/index.js] file written with same contents +//// [/src/core/tsconfig.tsbuildinfo] file written with same contents +//// [/src/logic/index.d.ts] file written with same contents +//// [/src/logic/index.js] file written with same contents +//// [/src/logic/index.js.map] file written with same contents +//// [/src/logic/tsconfig.tsbuildinfo] file written with same contents +//// [/src/tests/index.d.ts] file written with same contents +//// [/src/tests/index.js] file written with same contents +//// [/src/tests/tsconfig.tsbuildinfo] file written with same contents diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/rebuilds-when-extended-config-file-changes.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/rebuilds-when-extended-config-file-changes.js new file mode 100644 index 00000000000..ff22ad2e032 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/rebuilds-when-extended-config-file-changes.js @@ -0,0 +1,84 @@ +//// [/lib/incremental-declaration-changesOutput.txt] +/lib/tsc --b /src/tests --verbose +12:04:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/logic/tsconfig.json + * src/tests/tsconfig.json + +12:04:00 AM - Project 'src/core/tsconfig.json' is up to date because newest input 'src/core/anotherModule.ts' is older than oldest output 'src/core/anotherModule.js' + +12:04:00 AM - Project 'src/logic/tsconfig.json' is up to date because newest input 'src/logic/index.ts' is older than oldest output 'src/logic/index.js' + +12:04:00 AM - Project 'src/tests/tsconfig.json' is out of date because oldest output 'src/tests/index.js' is older than newest input 'src/tests/tsconfig.base.json' + +12:04:00 AM - Building project '/src/tests/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/tests/index.d.ts] file written with same contents +//// [/src/tests/index.js] file written with same contents +//// [/src/tests/tsconfig.base.json] +{"compilerOptions":{}} + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "../logic/index.ts": { + "version": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + }, + "./index.ts": { + "version": "12336236525-import * as c from '../core/index';\r\nimport * as logic from '../logic/index';\r\n\r\nc.leftPad(\"\", 10);\r\nlogic.getSecondsInDay();\r\n\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-9209611-import * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts", + "../logic/index.d.ts" + ] + }, + "exportedModulesMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "../logic/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/rebuilds-when-tsconfig-changes.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/rebuilds-when-tsconfig-changes.js new file mode 100644 index 00000000000..577edf20fe5 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/rebuilds-when-tsconfig-changes.js @@ -0,0 +1,97 @@ +//// [/lib/incremental-declaration-changesOutput.txt] +/lib/tsc --b /src/tests --verbose +12:20:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/logic/tsconfig.json + * src/tests/tsconfig.json + +12:20:00 AM - Project 'src/core/tsconfig.json' is up to date because newest input 'src/core/anotherModule.ts' is older than oldest output 'src/core/anotherModule.js' + +12:20:00 AM - Project 'src/logic/tsconfig.json' is up to date because newest input 'src/logic/index.ts' is older than oldest output 'src/logic/index.js' + +12:20:00 AM - Project 'src/tests/tsconfig.json' is out of date because oldest output 'src/tests/index.js' is older than newest input 'src/tests/tsconfig.json' + +12:20:00 AM - Building project '/src/tests/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/tests/index.d.ts] file written with same contents +//// [/src/tests/index.js] file written with same contents +//// [/src/tests/tsconfig.json] +{ + "references": [ + { "path": "../core" }, + { "path": "../logic" } + ], + "files": ["index.ts"], + "compilerOptions": { + "composite": true, "target": "es3", + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true + } +} + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "../logic/index.ts": { + "version": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + }, + "./index.ts": { + "version": "12336236525-import * as c from '../core/index';\r\nimport * as logic from '../logic/index';\r\n\r\nc.leftPad(\"\", 10);\r\nlogic.getSecondsInDay();\r\n\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-9209611-import * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "target": 0, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts", + "../logic/index.d.ts" + ] + }, + "exportedModulesMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "../logic/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/sample.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/sample.js index 94a962ebe02..0796602e3f9 100644 --- a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/sample.js +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/sample.js @@ -19,7 +19,7 @@ 12:04:00 AM - Building project '/src/tests/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/tests/tsconfig.json": 1, "/src/core/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-declaration-option-changes.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-declaration-option-changes.js index 2311e64ef2b..529acb4d78a 100644 --- a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-declaration-option-changes.js +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-declaration-option-changes.js @@ -7,7 +7,7 @@ 12:04:00 AM - Building project '/src/core/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/core/anotherModule.d.ts] diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-esModuleInterop-option-changes.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-esModuleInterop-option-changes.js index dd48841c8af..70113328193 100644 --- a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-esModuleInterop-option-changes.js +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-esModuleInterop-option-changes.js @@ -13,7 +13,7 @@ 12:04:00 AM - Building project '/src/tests/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/tests/index.d.ts] file written with same contents diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-logic-config-changes-declaration-dir.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-logic-config-changes-declaration-dir.js index da943e101e2..275c807f66f 100644 --- a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-logic-config-changes-declaration-dir.js +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-logic-config-changes-declaration-dir.js @@ -15,7 +15,7 @@ 12:12:00 AM - Building project '/src/tests/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/tests/tsconfig.json": 1, "/src/core/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-module-option-changes.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-module-option-changes.js index 0a801843705..03b378879dc 100644 --- a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-module-option-changes.js +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-module-option-changes.js @@ -7,7 +7,7 @@ 12:04:00 AM - Building project '/src/core/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/core/anotherModule.js] diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-target-option-changes.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-target-option-changes.js index bc3a7921993..b28623d38ed 100644 --- a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-target-option-changes.js +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-changes/when-target-option-changes.js @@ -15,7 +15,7 @@ TSFILE: /src/core/tsconfig.tsbuildinfo /src/core/anotherModule.ts /src/core/index.ts /src/core/some_decl.d.ts -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/core/anotherModule.js] diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/Only-builds-the-leaf-node-project.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/Only-builds-the-leaf-node-project.js new file mode 100644 index 00000000000..74ee0a5d2c8 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/Only-builds-the-leaf-node-project.js @@ -0,0 +1,59 @@ +//// [/lib/incremental-declaration-doesnt-changeOutput.txt] +/lib/tsc --b /src/tests --verbose +12:04:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/logic/tsconfig.json + * src/tests/tsconfig.json + +12:04:00 AM - Project 'src/core/tsconfig.json' is up to date because newest input 'src/core/anotherModule.ts' is older than oldest output 'src/core/anotherModule.js' + +12:04:00 AM - Project 'src/logic/tsconfig.json' is up to date because newest input 'src/logic/index.ts' is older than oldest output 'src/logic/index.js' + +12:04:00 AM - Project 'src/tests/tsconfig.json' is out of date because oldest output 'src/tests/index.js' is older than newest input 'src/tests/index.ts' + +12:04:00 AM - Building project '/src/tests/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/tests/index.d.ts] +declare const m = 10; + + +//// [/src/tests/index.js] +var m = 10; + + +//// [/src/tests/index.ts] +const m = 10; + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./index.ts": { + "version": "3708260210-const m = 10;", + "signature": "1073907769-declare const m = 10;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/indicates-that-it-would-skip-builds-during-a-dry-build.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/indicates-that-it-would-skip-builds-during-a-dry-build.js new file mode 100644 index 00000000000..3e323c17d3e --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/indicates-that-it-would-skip-builds-during-a-dry-build.js @@ -0,0 +1,11 @@ +//// [/lib/incremental-declaration-doesnt-changeOutput.txt] +/lib/tsc --b /src/tests --dry +12:12:00 AM - Project '/src/core/tsconfig.json' is up to date + +12:12:00 AM - Project '/src/logic/tsconfig.json' is up to date + +12:12:00 AM - Project '/src/tests/tsconfig.json' is up to date + +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/sample.js b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/sample.js index a2d9e5a8564..04b80d55cbc 100644 --- a/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/sample.js +++ b/tests/baselines/reference/tsbuild/sample1/incremental-declaration-doesnt-change/sample.js @@ -19,7 +19,7 @@ 12:08:00 AM - Updating output timestamps of project '/src/tests/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/tests/tsconfig.json": 1, "/src/core/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/always-builds-under-with-force-option.js b/tests/baselines/reference/tsbuild/sample1/initial-build/always-builds-under-with-force-option.js new file mode 100644 index 00000000000..7184dc584e6 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/always-builds-under-with-force-option.js @@ -0,0 +1,225 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests --force +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] +export declare const World = "hello"; +//# sourceMappingURL=anotherModule.d.ts.map + +//// [/src/core/anotherModule.d.ts.map] +{"version":3,"file":"anotherModule.d.ts","sourceRoot":"","sources":["anotherModule.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAC"} + +//// [/src/core/anotherModule.js] +"use strict"; +exports.__esModule = true; +exports.World = "hello"; + + +//// [/src/core/index.d.ts] +export declare const someString: string; +export declare function leftPad(s: string, n: number): string; +export declare function multiply(a: number, b: number): number; +//# sourceMappingURL=index.d.ts.map + +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,EAAE,MAAsB,CAAC;AAChD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB;AAC/D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +exports.someString = "HELLO WORLD"; +function leftPad(s, n) { return s + n; } +exports.leftPad = leftPad; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./anothermodule.ts": { + "version": "-2676574883-export const World = \"hello\";\r\n", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "./some_decl.d.ts": { + "version": "-9253692965-declare const dts: any;\r\n", + "signature": "-9253692965-declare const dts: any;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./anothermodule.ts", + "./index.ts", + "./some_decl.d.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/logic/index.d.ts] +export declare function getSecondsInDay(): number; +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/logic/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +function getSecondsInDay() { + return c.multiply(10, 15); +} +exports.getSecondsInDay = getSecondsInDay; +var mod = require("../core/anotherModule"); +exports.m = mod; +//# sourceMappingURL=index.js.map + +//// [/src/logic/index.js.map] +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;AAAA,iCAAmC;AACnC,SAAgB,eAAe;IAC3B,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9B,CAAC;AAFD,0CAEC;AACD,2CAA6C;AAChC,QAAA,CAAC,GAAG,GAAG,CAAC"} + +//// [/src/logic/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-5786964698-import * as c from '../core/index';\r\nexport function getSecondsInDay() {\r\n return c.multiply(10, 15);\r\n}\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "sourceMap": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts" + ] + }, + "exportedModulesMap": { + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tests/index.d.ts] +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/tests/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +var logic = require("../logic/index"); +c.leftPad("", 10); +logic.getSecondsInDay(); +var mod = require("../core/anotherModule"); +exports.m = mod; + + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "../logic/index.ts": { + "version": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + }, + "./index.ts": { + "version": "12336236525-import * as c from '../core/index';\r\nimport * as logic from '../logic/index';\r\n\r\nc.leftPad(\"\", 10);\r\nlogic.getSecondsInDay();\r\n\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-9209611-import * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts", + "../logic/index.d.ts" + ] + }, + "exportedModulesMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "../logic/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/builds-correctly-when-declarationDir-is-specified.js b/tests/baselines/reference/tsbuild/sample1/initial-build/builds-correctly-when-declarationDir-is-specified.js new file mode 100644 index 00000000000..6f9e05fdb69 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/builds-correctly-when-declarationDir-is-specified.js @@ -0,0 +1,227 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] +export declare const World = "hello"; +//# sourceMappingURL=anotherModule.d.ts.map + +//// [/src/core/anotherModule.d.ts.map] +{"version":3,"file":"anotherModule.d.ts","sourceRoot":"","sources":["anotherModule.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAC"} + +//// [/src/core/anotherModule.js] +"use strict"; +exports.__esModule = true; +exports.World = "hello"; + + +//// [/src/core/index.d.ts] +export declare const someString: string; +export declare function leftPad(s: string, n: number): string; +export declare function multiply(a: number, b: number): number; +//# sourceMappingURL=index.d.ts.map + +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,EAAE,MAAsB,CAAC;AAChD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB;AAC/D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +exports.someString = "HELLO WORLD"; +function leftPad(s, n) { return s + n; } +exports.leftPad = leftPad; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./anothermodule.ts": { + "version": "-2676574883-export const World = \"hello\";\r\n", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "./some_decl.d.ts": { + "version": "-9253692965-declare const dts: any;\r\n", + "signature": "-9253692965-declare const dts: any;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./anothermodule.ts", + "./index.ts", + "./some_decl.d.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/logic/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +function getSecondsInDay() { + return c.multiply(10, 15); +} +exports.getSecondsInDay = getSecondsInDay; +var mod = require("../core/anotherModule"); +exports.m = mod; +//# sourceMappingURL=index.js.map + +//// [/src/logic/index.js.map] +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;AAAA,iCAAmC;AACnC,SAAgB,eAAe;IAC3B,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9B,CAAC;AAFD,0CAEC;AACD,2CAA6C;AAChC,QAAA,CAAC,GAAG,GAAG,CAAC"} + +//// [/src/logic/out/decls/index.d.ts] +export declare function getSecondsInDay(): number; +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/logic/tsconfig.json] +{"compilerOptions":{"composite":true,"declaration":true,"sourceMap":true,"declarationDir":"out/decls"},"references":[{"path":"../core"}]} + +//// [/src/logic/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-5786964698-import * as c from '../core/index';\r\nexport function getSecondsInDay() {\r\n return c.multiply(10, 15);\r\n}\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "sourceMap": true, + "declarationDir": "./out/decls", + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts" + ] + }, + "exportedModulesMap": { + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tests/index.d.ts] +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/tests/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +var logic = require("../logic/index"); +c.leftPad("", 10); +logic.getSecondsInDay(); +var mod = require("../core/anotherModule"); +exports.m = mod; + + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "../logic/index.ts": { + "version": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + }, + "./index.ts": { + "version": "12336236525-import * as c from '../core/index';\r\nimport * as logic from '../logic/index';\r\n\r\nc.leftPad(\"\", 10);\r\nlogic.getSecondsInDay();\r\n\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-9209611-import * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts", + "../logic/out/decls/index.d.ts" + ] + }, + "exportedModulesMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "../logic/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/builds-correctly-when-outDir-is-specified.js b/tests/baselines/reference/tsbuild/sample1/initial-build/builds-correctly-when-outDir-is-specified.js new file mode 100644 index 00000000000..b61004ba7b1 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/builds-correctly-when-outDir-is-specified.js @@ -0,0 +1,227 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] +export declare const World = "hello"; +//# sourceMappingURL=anotherModule.d.ts.map + +//// [/src/core/anotherModule.d.ts.map] +{"version":3,"file":"anotherModule.d.ts","sourceRoot":"","sources":["anotherModule.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAC"} + +//// [/src/core/anotherModule.js] +"use strict"; +exports.__esModule = true; +exports.World = "hello"; + + +//// [/src/core/index.d.ts] +export declare const someString: string; +export declare function leftPad(s: string, n: number): string; +export declare function multiply(a: number, b: number): number; +//# sourceMappingURL=index.d.ts.map + +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,EAAE,MAAsB,CAAC;AAChD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB;AAC/D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +exports.someString = "HELLO WORLD"; +function leftPad(s, n) { return s + n; } +exports.leftPad = leftPad; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./anothermodule.ts": { + "version": "-2676574883-export const World = \"hello\";\r\n", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "./some_decl.d.ts": { + "version": "-9253692965-declare const dts: any;\r\n", + "signature": "-9253692965-declare const dts: any;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./anothermodule.ts", + "./index.ts", + "./some_decl.d.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/logic/outDir/index.d.ts] +export declare function getSecondsInDay(): number; +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/logic/outDir/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +function getSecondsInDay() { + return c.multiply(10, 15); +} +exports.getSecondsInDay = getSecondsInDay; +var mod = require("../core/anotherModule"); +exports.m = mod; +//# sourceMappingURL=index.js.map + +//// [/src/logic/outDir/index.js.map] +{"version":3,"file":"index.js","sourceRoot":"","sources":["../index.ts"],"names":[],"mappings":";;AAAA,iCAAmC;AACnC,SAAgB,eAAe;IAC3B,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9B,CAAC;AAFD,0CAEC;AACD,2CAA6C;AAChC,QAAA,CAAC,GAAG,GAAG,CAAC"} + +//// [/src/logic/outDir/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "../index.ts": { + "version": "-5786964698-import * as c from '../core/index';\r\nexport function getSecondsInDay() {\r\n return c.multiply(10, 15);\r\n}\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "sourceMap": true, + "outDir": "./", + "configFilePath": "../tsconfig.json" + }, + "referencedMap": { + "../index.ts": [ + "../../core/anothermodule.d.ts", + "../../core/index.d.ts" + ] + }, + "exportedModulesMap": { + "../index.ts": [ + "../../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../../lib/lib.d.ts", + "../../core/anothermodule.ts", + "../../core/index.ts", + "../index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/logic/tsconfig.json] +{"compilerOptions":{"composite":true,"declaration":true,"sourceMap":true,"outDir":"outDir"},"references":[{"path":"../core"}]} + +//// [/src/tests/index.d.ts] +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/tests/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +var logic = require("../logic/index"); +c.leftPad("", 10); +logic.getSecondsInDay(); +var mod = require("../core/anotherModule"); +exports.m = mod; + + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "../logic/index.ts": { + "version": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + }, + "./index.ts": { + "version": "12336236525-import * as c from '../core/index';\r\nimport * as logic from '../logic/index';\r\n\r\nc.leftPad(\"\", 10);\r\nlogic.getSecondsInDay();\r\n\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-9209611-import * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts", + "../logic/outdir/index.d.ts" + ] + }, + "exportedModulesMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "../logic/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/builds-correctly-when-project-is-not-composite-or-doesnt-have-any-references.js b/tests/baselines/reference/tsbuild/sample1/initial-build/builds-correctly-when-project-is-not-composite-or-doesnt-have-any-references.js new file mode 100644 index 00000000000..78aae297847 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/builds-correctly-when-project-is-not-composite-or-doesnt-have-any-references.js @@ -0,0 +1,54 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/core --verbose +12:00:00 AM - Projects in this build: + * src/core/tsconfig.json + +12:00:00 AM - Project 'src/core/tsconfig.json' is out of date because output file 'src/core/anotherModule.js' does not exist + +12:00:00 AM - Building project '/src/core/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] +export declare const World = "hello"; +//# sourceMappingURL=anotherModule.d.ts.map + +//// [/src/core/anotherModule.d.ts.map] +{"version":3,"file":"anotherModule.d.ts","sourceRoot":"","sources":["anotherModule.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAC"} + +//// [/src/core/anotherModule.js] +"use strict"; +exports.__esModule = true; +exports.World = "hello"; + + +//// [/src/core/index.d.ts] +export declare const someString: string; +export declare function leftPad(s: string, n: number): string; +export declare function multiply(a: number, b: number): number; +//# sourceMappingURL=index.d.ts.map + +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,EAAE,MAAsB,CAAC;AAChD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB;AAC/D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +exports.someString = "HELLO WORLD"; +function leftPad(s, n) { return s + n; } +exports.leftPad = leftPad; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/tsconfig.json] +{ + "compilerOptions": { + + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true + } +} + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/can-detect-when-and-what-to-rebuild.js b/tests/baselines/reference/tsbuild/sample1/initial-build/can-detect-when-and-what-to-rebuild.js new file mode 100644 index 00000000000..e10434fa082 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/can-detect-when-and-what-to-rebuild.js @@ -0,0 +1,16 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests --verbose +12:01:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/logic/tsconfig.json + * src/tests/tsconfig.json + +12:01:00 AM - Project 'src/core/tsconfig.json' is up to date because newest input 'src/core/anotherModule.ts' is older than oldest output 'src/core/anotherModule.js' + +12:01:00 AM - Project 'src/logic/tsconfig.json' is up to date because newest input 'src/logic/index.ts' is older than oldest output 'src/logic/index.js' + +12:01:00 AM - Project 'src/tests/tsconfig.json' is up to date because newest input 'src/tests/index.ts' is older than oldest output 'src/tests/index.js' + +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/does-not-build-downstream-projects-if-upstream-projects-have-errors.js b/tests/baselines/reference/tsbuild/sample1/initial-build/does-not-build-downstream-projects-if-upstream-projects-have-errors.js new file mode 100644 index 00000000000..4e5f349c0a1 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/does-not-build-downstream-projects-if-upstream-projects-have-errors.js @@ -0,0 +1,104 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests --verbose +12:00:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/logic/tsconfig.json + * src/tests/tsconfig.json + +12:00:00 AM - Project 'src/core/tsconfig.json' is out of date because output file 'src/core/anotherModule.js' does not exist + +12:00:00 AM - Building project '/src/core/tsconfig.json'... + +12:00:00 AM - Project 'src/logic/tsconfig.json' is out of date because output file 'src/logic/index.js' does not exist + +12:00:00 AM - Building project '/src/logic/tsconfig.json'... + +src/logic/index.ts(3,14): error TS2339: Property 'muitply' does not exist on type 'typeof import("/src/core/index")'. +12:00:00 AM - Project 'src/tests/tsconfig.json' can't be built because its dependency 'src/logic' has errors + +12:00:00 AM - Skipping build of project '/src/tests/tsconfig.json' because its dependency '/src/logic' has errors + +exitCode:: ExitStatus.DiagnosticsPresent_OutputsGenerated + + +//// [/src/core/anotherModule.d.ts] +export declare const World = "hello"; +//# sourceMappingURL=anotherModule.d.ts.map + +//// [/src/core/anotherModule.d.ts.map] +{"version":3,"file":"anotherModule.d.ts","sourceRoot":"","sources":["anotherModule.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAC"} + +//// [/src/core/anotherModule.js] +"use strict"; +exports.__esModule = true; +exports.World = "hello"; + + +//// [/src/core/index.d.ts] +export declare const someString: string; +export declare function leftPad(s: string, n: number): string; +export declare function multiply(a: number, b: number): number; +//# sourceMappingURL=index.d.ts.map + +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,EAAE,MAAsB,CAAC;AAChD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB;AAC/D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +exports.someString = "HELLO WORLD"; +function leftPad(s, n) { return s + n; } +exports.leftPad = leftPad; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./anothermodule.ts": { + "version": "-2676574883-export const World = \"hello\";\r\n", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "./some_decl.d.ts": { + "version": "-9253692965-declare const dts: any;\r\n", + "signature": "-9253692965-declare const dts: any;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./anothermodule.ts", + "./index.ts", + "./some_decl.d.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/logic/index.ts] +import * as c from '../core/index'; +export function getSecondsInDay() { + return c.muitply(); +} +import * as mod from '../core/anotherModule'; +export const m = mod; + + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/does-not-write-any-files-in-a-dry-build.js b/tests/baselines/reference/tsbuild/sample1/initial-build/does-not-write-any-files-in-a-dry-build.js new file mode 100644 index 00000000000..660696d2437 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/does-not-write-any-files-in-a-dry-build.js @@ -0,0 +1,11 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests --dry +12:00:00 AM - A non-dry build would build project '/src/core/tsconfig.json' + +12:00:00 AM - A non-dry build would build project '/src/logic/tsconfig.json' + +12:00:00 AM - A non-dry build would build project '/src/tests/tsconfig.json' + +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/listEmittedFiles.js b/tests/baselines/reference/tsbuild/sample1/initial-build/listEmittedFiles.js new file mode 100644 index 00000000000..e9fb72c132e --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/listEmittedFiles.js @@ -0,0 +1,242 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests --listEmittedFiles +TSFILE: /src/core/anotherModule.js +TSFILE: /src/core/anotherModule.d.ts.map +TSFILE: /src/core/anotherModule.d.ts +TSFILE: /src/core/index.js +TSFILE: /src/core/index.d.ts.map +TSFILE: /src/core/index.d.ts +TSFILE: /src/core/tsconfig.tsbuildinfo +TSFILE: /src/logic/index.js.map +TSFILE: /src/logic/index.js +TSFILE: /src/logic/index.d.ts +TSFILE: /src/logic/tsconfig.tsbuildinfo +TSFILE: /src/tests/index.js +TSFILE: /src/tests/index.d.ts +TSFILE: /src/tests/tsconfig.tsbuildinfo +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] +export declare const World = "hello"; +//# sourceMappingURL=anotherModule.d.ts.map + +//// [/src/core/anotherModule.d.ts.map] +{"version":3,"file":"anotherModule.d.ts","sourceRoot":"","sources":["anotherModule.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAC"} + +//// [/src/core/anotherModule.js] +"use strict"; +exports.__esModule = true; +exports.World = "hello"; + + +//// [/src/core/index.d.ts] +export declare const someString: string; +export declare function leftPad(s: string, n: number): string; +export declare function multiply(a: number, b: number): number; +//# sourceMappingURL=index.d.ts.map + +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,EAAE,MAAsB,CAAC;AAChD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB;AAC/D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +exports.someString = "HELLO WORLD"; +function leftPad(s, n) { return s + n; } +exports.leftPad = leftPad; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./anothermodule.ts": { + "version": "-2676574883-export const World = \"hello\";\r\n", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "./some_decl.d.ts": { + "version": "-9253692965-declare const dts: any;\r\n", + "signature": "-9253692965-declare const dts: any;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "listEmittedFiles": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./anothermodule.ts", + "./index.ts", + "./some_decl.d.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/logic/index.d.ts] +export declare function getSecondsInDay(): number; +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/logic/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +function getSecondsInDay() { + return c.multiply(10, 15); +} +exports.getSecondsInDay = getSecondsInDay; +var mod = require("../core/anotherModule"); +exports.m = mod; +//# sourceMappingURL=index.js.map + +//// [/src/logic/index.js.map] +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;AAAA,iCAAmC;AACnC,SAAgB,eAAe;IAC3B,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9B,CAAC;AAFD,0CAEC;AACD,2CAA6C;AAChC,QAAA,CAAC,GAAG,GAAG,CAAC"} + +//// [/src/logic/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-5786964698-import * as c from '../core/index';\r\nexport function getSecondsInDay() {\r\n return c.multiply(10, 15);\r\n}\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "sourceMap": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "listEmittedFiles": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts" + ] + }, + "exportedModulesMap": { + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tests/index.d.ts] +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/tests/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +var logic = require("../logic/index"); +c.leftPad("", 10); +logic.getSecondsInDay(); +var mod = require("../core/anotherModule"); +exports.m = mod; + + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "../logic/index.ts": { + "version": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + }, + "./index.ts": { + "version": "12336236525-import * as c from '../core/index';\r\nimport * as logic from '../logic/index';\r\n\r\nc.leftPad(\"\", 10);\r\nlogic.getSecondsInDay();\r\n\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-9209611-import * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "listEmittedFiles": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts", + "../logic/index.d.ts" + ] + }, + "exportedModulesMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "../logic/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/listFiles.js b/tests/baselines/reference/tsbuild/sample1/initial-build/listFiles.js new file mode 100644 index 00000000000..9e44bb99bd4 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/listFiles.js @@ -0,0 +1,241 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests --listFiles +/lib/lib.d.ts +/src/core/anotherModule.ts +/src/core/index.ts +/src/core/some_decl.d.ts +/lib/lib.d.ts +/src/core/index.d.ts +/src/core/anotherModule.d.ts +/src/logic/index.ts +/lib/lib.d.ts +/src/core/index.d.ts +/src/core/anotherModule.d.ts +/src/logic/index.d.ts +/src/tests/index.ts +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] +export declare const World = "hello"; +//# sourceMappingURL=anotherModule.d.ts.map + +//// [/src/core/anotherModule.d.ts.map] +{"version":3,"file":"anotherModule.d.ts","sourceRoot":"","sources":["anotherModule.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAC"} + +//// [/src/core/anotherModule.js] +"use strict"; +exports.__esModule = true; +exports.World = "hello"; + + +//// [/src/core/index.d.ts] +export declare const someString: string; +export declare function leftPad(s: string, n: number): string; +export declare function multiply(a: number, b: number): number; +//# sourceMappingURL=index.d.ts.map + +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,EAAE,MAAsB,CAAC;AAChD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB;AAC/D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +exports.someString = "HELLO WORLD"; +function leftPad(s, n) { return s + n; } +exports.leftPad = leftPad; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./anothermodule.ts": { + "version": "-2676574883-export const World = \"hello\";\r\n", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "./some_decl.d.ts": { + "version": "-9253692965-declare const dts: any;\r\n", + "signature": "-9253692965-declare const dts: any;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "listFiles": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./anothermodule.ts", + "./index.ts", + "./some_decl.d.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/logic/index.d.ts] +export declare function getSecondsInDay(): number; +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/logic/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +function getSecondsInDay() { + return c.multiply(10, 15); +} +exports.getSecondsInDay = getSecondsInDay; +var mod = require("../core/anotherModule"); +exports.m = mod; +//# sourceMappingURL=index.js.map + +//// [/src/logic/index.js.map] +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;AAAA,iCAAmC;AACnC,SAAgB,eAAe;IAC3B,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9B,CAAC;AAFD,0CAEC;AACD,2CAA6C;AAChC,QAAA,CAAC,GAAG,GAAG,CAAC"} + +//// [/src/logic/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-5786964698-import * as c from '../core/index';\r\nexport function getSecondsInDay() {\r\n return c.multiply(10, 15);\r\n}\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "sourceMap": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "listFiles": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts" + ] + }, + "exportedModulesMap": { + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tests/index.d.ts] +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/tests/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +var logic = require("../logic/index"); +c.leftPad("", 10); +logic.getSecondsInDay(); +var mod = require("../core/anotherModule"); +exports.m = mod; + + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "../logic/index.ts": { + "version": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + }, + "./index.ts": { + "version": "12336236525-import * as c from '../core/index';\r\nimport * as logic from '../logic/index';\r\n\r\nc.leftPad(\"\", 10);\r\nlogic.getSecondsInDay();\r\n\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-9209611-import * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "listFiles": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts", + "../logic/index.d.ts" + ] + }, + "exportedModulesMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "../logic/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/rebuilds-when-extended-config-file-changes.js b/tests/baselines/reference/tsbuild/sample1/initial-build/rebuilds-when-extended-config-file-changes.js new file mode 100644 index 00000000000..d36e53f292e --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/rebuilds-when-extended-config-file-changes.js @@ -0,0 +1,261 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests --verbose +12:01:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/logic/tsconfig.json + * src/tests/tsconfig.json + +12:01:00 AM - Project 'src/core/tsconfig.json' is out of date because output file 'src/core/anotherModule.js' does not exist + +12:01:00 AM - Building project '/src/core/tsconfig.json'... + +12:01:00 AM - Project 'src/logic/tsconfig.json' is out of date because output file 'src/logic/index.js' does not exist + +12:01:00 AM - Building project '/src/logic/tsconfig.json'... + +12:01:00 AM - Project 'src/tests/tsconfig.json' is out of date because output file 'src/tests/index.js' does not exist + +12:01:00 AM - Building project '/src/tests/tsconfig.json'... + +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] +export declare const World = "hello"; +//# sourceMappingURL=anotherModule.d.ts.map + +//// [/src/core/anotherModule.d.ts.map] +{"version":3,"file":"anotherModule.d.ts","sourceRoot":"","sources":["anotherModule.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,KAAK,UAAU,CAAC"} + +//// [/src/core/anotherModule.js] +"use strict"; +exports.__esModule = true; +exports.World = "hello"; + + +//// [/src/core/index.d.ts] +export declare const someString: string; +export declare function leftPad(s: string, n: number): string; +export declare function multiply(a: number, b: number): number; +//# sourceMappingURL=index.d.ts.map + +//// [/src/core/index.d.ts.map] +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,UAAU,EAAE,MAAsB,CAAC;AAChD,wBAAgB,OAAO,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB;AAC/D,wBAAgB,QAAQ,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,EAAE,MAAM,UAAmB"} + +//// [/src/core/index.js] +"use strict"; +exports.__esModule = true; +exports.someString = "HELLO WORLD"; +function leftPad(s, n) { return s + n; } +exports.leftPad = leftPad; +function multiply(a, b) { return a * b; } +exports.multiply = multiply; + + +//// [/src/core/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./anothermodule.ts": { + "version": "-2676574883-export const World = \"hello\";\r\n", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-18749805970-export const someString: string = \"HELLO WORLD\";\r\nexport function leftPad(s: string, n: number) { return s + n; }\r\nexport function multiply(a: number, b: number) { return a * b; }\r\n", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "./some_decl.d.ts": { + "version": "-9253692965-declare const dts: any;\r\n", + "signature": "-9253692965-declare const dts: any;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "declarationMap": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./anothermodule.ts", + "./index.ts", + "./some_decl.d.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/logic/index.d.ts] +export declare function getSecondsInDay(): number; +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/logic/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +function getSecondsInDay() { + return c.multiply(10, 15); +} +exports.getSecondsInDay = getSecondsInDay; +var mod = require("../core/anotherModule"); +exports.m = mod; +//# sourceMappingURL=index.js.map + +//// [/src/logic/index.js.map] +{"version":3,"file":"index.js","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":";;AAAA,iCAAmC;AACnC,SAAgB,eAAe;IAC3B,OAAO,CAAC,CAAC,QAAQ,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC;AAC9B,CAAC;AAFD,0CAEC;AACD,2CAA6C;AAChC,QAAA,CAAC,GAAG,GAAG,CAAC"} + +//// [/src/logic/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "./index.ts": { + "version": "-5786964698-import * as c from '../core/index';\r\nexport function getSecondsInDay() {\r\n return c.multiply(10, 15);\r\n}\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "composite": true, + "declaration": true, + "sourceMap": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts" + ] + }, + "exportedModulesMap": { + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tests/index.d.ts] +import * as mod from '../core/anotherModule'; +export declare const m: typeof mod; + + +//// [/src/tests/index.js] +"use strict"; +exports.__esModule = true; +var c = require("../core/index"); +var logic = require("../logic/index"); +c.leftPad("", 10); +logic.getSecondsInDay(); +var mod = require("../core/anotherModule"); +exports.m = mod; + + +//// [/src/tests/tsconfig.base.json] +{"compilerOptions":{"target":"es3"}} + +//// [/src/tests/tsconfig.json] +{ + "extends": "./tsconfig.base.json", "references": [ + { "path": "../core" }, + { "path": "../logic" } + ], + "files": ["index.ts"], + "compilerOptions": { + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true + } +} + +//// [/src/tests/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../core/index.ts": { + "version": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map", + "signature": "-13851440507-export declare const someString: string;\r\nexport declare function leftPad(s: string, n: number): string;\r\nexport declare function multiply(a: number, b: number): number;\r\n//# sourceMappingURL=index.d.ts.map" + }, + "../core/anothermodule.ts": { + "version": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map", + "signature": "7652028357-export declare const World = \"hello\";\r\n//# sourceMappingURL=anotherModule.d.ts.map" + }, + "../logic/index.ts": { + "version": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n", + "signature": "-6548680073-export declare function getSecondsInDay(): number;\r\nimport * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + }, + "./index.ts": { + "version": "12336236525-import * as c from '../core/index';\r\nimport * as logic from '../logic/index';\r\n\r\nc.leftPad(\"\", 10);\r\nlogic.getSecondsInDay();\r\n\r\nimport * as mod from '../core/anotherModule';\r\nexport const m = mod;\r\n", + "signature": "-9209611-import * as mod from '../core/anotherModule';\r\nexport declare const m: typeof mod;\r\n" + } + }, + "options": { + "target": 0, + "composite": true, + "declaration": true, + "forceConsistentCasingInFileNames": true, + "skipDefaultLibCheck": true, + "configFilePath": "./tsconfig.json" + }, + "referencedMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts", + "../core/index.d.ts", + "../logic/index.d.ts" + ] + }, + "exportedModulesMap": { + "../logic/index.ts": [ + "../core/anothermodule.d.ts" + ], + "./index.ts": [ + "../core/anothermodule.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "../core/anothermodule.ts", + "../core/index.ts", + "../logic/index.ts", + "./index.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/removes-all-files-it-built.js b/tests/baselines/reference/tsbuild/sample1/initial-build/removes-all-files-it-built.js new file mode 100644 index 00000000000..de8181610b6 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/removes-all-files-it-built.js @@ -0,0 +1,19 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tests --clean +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] unlink +//// [/src/core/anotherModule.d.ts.map] unlink +//// [/src/core/anotherModule.js] unlink +//// [/src/core/index.d.ts] unlink +//// [/src/core/index.d.ts.map] unlink +//// [/src/core/index.js] unlink +//// [/src/core/tsconfig.tsbuildinfo] unlink +//// [/src/logic/index.d.ts] unlink +//// [/src/logic/index.js] unlink +//// [/src/logic/index.js.map] unlink +//// [/src/logic/tsconfig.tsbuildinfo] unlink +//// [/src/tests/index.d.ts] unlink +//// [/src/tests/index.js] unlink +//// [/src/tests/tsconfig.tsbuildinfo] unlink diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/sample.js b/tests/baselines/reference/tsbuild/sample1/initial-build/sample.js index 00228056483..6dec9d74cd3 100644 --- a/tests/baselines/reference/tsbuild/sample1/initial-build/sample.js +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/sample.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/tests/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/tests/tsconfig.json": 1, "/src/core/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/when-declaration-option-changes.js b/tests/baselines/reference/tsbuild/sample1/initial-build/when-declaration-option-changes.js index 6fcba548d3b..6973a1605d1 100644 --- a/tests/baselines/reference/tsbuild/sample1/initial-build/when-declaration-option-changes.js +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/when-declaration-option-changes.js @@ -7,7 +7,7 @@ 12:01:00 AM - Building project '/src/core/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/core/anotherModule.js] diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/when-esModuleInterop-option-changes.js b/tests/baselines/reference/tsbuild/sample1/initial-build/when-esModuleInterop-option-changes.js index 0f1ea65c5e4..5a11e363bfd 100644 --- a/tests/baselines/reference/tsbuild/sample1/initial-build/when-esModuleInterop-option-changes.js +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/when-esModuleInterop-option-changes.js @@ -17,7 +17,7 @@ 12:01:00 AM - Building project '/src/tests/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/core/anotherModule.d.ts] diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/when-logic-specifies-tsBuildInfoFile.js b/tests/baselines/reference/tsbuild/sample1/initial-build/when-logic-specifies-tsBuildInfoFile.js index fe60d8093d4..a448bcf3054 100644 --- a/tests/baselines/reference/tsbuild/sample1/initial-build/when-logic-specifies-tsBuildInfoFile.js +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/when-logic-specifies-tsBuildInfoFile.js @@ -17,7 +17,7 @@ 12:00:00 AM - Building project '/src/tests/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success readFiles:: { "/src/tests/tsconfig.json": 1, "/src/core/tsconfig.json": 1, diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/when-module-option-changes.js b/tests/baselines/reference/tsbuild/sample1/initial-build/when-module-option-changes.js index c890f0d5766..d4692e872c2 100644 --- a/tests/baselines/reference/tsbuild/sample1/initial-build/when-module-option-changes.js +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/when-module-option-changes.js @@ -7,7 +7,7 @@ 12:01:00 AM - Building project '/src/core/tsconfig.json'... -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/core/anotherModule.js] diff --git a/tests/baselines/reference/tsbuild/sample1/initial-build/when-target-option-changes.js b/tests/baselines/reference/tsbuild/sample1/initial-build/when-target-option-changes.js index c615f77eb86..fcbcb2bbcb6 100644 --- a/tests/baselines/reference/tsbuild/sample1/initial-build/when-target-option-changes.js +++ b/tests/baselines/reference/tsbuild/sample1/initial-build/when-target-option-changes.js @@ -15,7 +15,7 @@ TSFILE: /src/core/tsconfig.tsbuildinfo /src/core/anotherModule.ts /src/core/index.ts /src/core/some_decl.d.ts -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/lib/lib.d.ts] diff --git a/tests/baselines/reference/tsbuild/sample1/no-change-run/always-builds-under-with-force-option.js b/tests/baselines/reference/tsbuild/sample1/no-change-run/always-builds-under-with-force-option.js new file mode 100644 index 00000000000..447a8dbcc1f --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/no-change-run/always-builds-under-with-force-option.js @@ -0,0 +1,19 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --b /src/tests --force +exitCode:: ExitStatus.Success + + +//// [/src/core/anotherModule.d.ts] file written with same contents +//// [/src/core/anotherModule.d.ts.map] file written with same contents +//// [/src/core/anotherModule.js] file written with same contents +//// [/src/core/index.d.ts] file written with same contents +//// [/src/core/index.d.ts.map] file written with same contents +//// [/src/core/index.js] file written with same contents +//// [/src/core/tsconfig.tsbuildinfo] file written with same contents +//// [/src/logic/index.d.ts] file written with same contents +//// [/src/logic/index.js] file written with same contents +//// [/src/logic/index.js.map] file written with same contents +//// [/src/logic/tsconfig.tsbuildinfo] file written with same contents +//// [/src/tests/index.d.ts] file written with same contents +//// [/src/tests/index.js] file written with same contents +//// [/src/tests/tsconfig.tsbuildinfo] file written with same contents diff --git a/tests/baselines/reference/tsbuild/sample1/no-change-run/removes-all-files-it-built.js b/tests/baselines/reference/tsbuild/sample1/no-change-run/removes-all-files-it-built.js new file mode 100644 index 00000000000..b0b052304a2 --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/no-change-run/removes-all-files-it-built.js @@ -0,0 +1,5 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --b /src/tests --clean +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsbuild/sample1/no-change-run/sample.js b/tests/baselines/reference/tsbuild/sample1/no-change-run/sample.js new file mode 100644 index 00000000000..8304e0bf57c --- /dev/null +++ b/tests/baselines/reference/tsbuild/sample1/no-change-run/sample.js @@ -0,0 +1,23 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --b /src/tests --verbose +12:16:00 AM - Projects in this build: + * src/core/tsconfig.json + * src/logic/tsconfig.json + * src/tests/tsconfig.json + +12:16:00 AM - Project 'src/core/tsconfig.json' is up to date because newest input 'src/core/anotherModule.ts' is older than oldest output 'src/core/anotherModule.js' + +12:16:00 AM - Project 'src/logic/tsconfig.json' is up to date because newest input 'src/logic/index.ts' is older than oldest output 'src/logic/index.js' + +12:16:00 AM - Project 'src/tests/tsconfig.json' is up to date because newest input 'src/tests/index.ts' is older than oldest output 'src/tests/index.js' + +exitCode:: ExitStatus.Success +readFiles:: { + "/src/tests/tsconfig.json": 1, + "/src/core/tsconfig.json": 1, + "/src/logic/tsconfig.json": 1, + "/src/core/tsconfig.tsbuildinfo": 1, + "/src/logic/tsconfig.tsbuildinfo": 1, + "/src/tests/tsconfig.tsbuildinfo": 1 +} + diff --git a/tests/baselines/reference/tsbuild/transitiveReferences/initial-build/builds-correctly-when-the-referenced-project-uses-different-module-resolution.js b/tests/baselines/reference/tsbuild/transitiveReferences/initial-build/builds-correctly-when-the-referenced-project-uses-different-module-resolution.js new file mode 100644 index 00000000000..aaa2ca6695e --- /dev/null +++ b/tests/baselines/reference/tsbuild/transitiveReferences/initial-build/builds-correctly-when-the-referenced-project-uses-different-module-resolution.js @@ -0,0 +1,129 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig.c.json --listFiles +/lib/lib.d.ts +/src/a.ts +/lib/lib.d.ts +/src/a.d.ts +/src/b.ts +/lib/lib.d.ts +/src/a.d.ts +/src/b.d.ts +/src/refs/a.d.ts +/src/c.ts +exitCode:: ExitStatus.Success + + +//// [/src/a.d.ts] +export declare class A { +} + + +//// [/src/a.js] +"use strict"; +exports.__esModule = true; +var A = /** @class */ (function () { + function A() { + } + return A; +}()); +exports.A = A; + + +//// [/src/b.d.ts] +import { A } from 'a'; +export declare const b: A; + + +//// [/src/b.js] +"use strict"; +exports.__esModule = true; +var a_1 = require("a"); +exports.b = new a_1.A(); + + +//// [/src/b.ts] +import {A} from 'a'; +export const b = new A(); + +//// [/src/c.js] +"use strict"; +exports.__esModule = true; +var b_1 = require("./b"); +var a_1 = require("@ref/a"); +b_1.b; +a_1.X; + + +//// [/src/tsconfig.a.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./a.ts": { + "version": "-8566332115-export class A {}\r\n", + "signature": "-9529994156-export declare class A {\r\n}\r\n" + } + }, + "options": { + "composite": true, + "listFiles": true, + "configFilePath": "./tsconfig.a.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../lib/lib.d.ts", + "./a.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tsconfig.b.json] +{"compilerOptions":{"composite":true,"moduleResolution":"classic"},"files":["b.ts"],"references":[{"path":"tsconfig.a.json"}]} + +//// [/src/tsconfig.b.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./a.ts": { + "version": "-9529994156-export declare class A {\r\n}\r\n", + "signature": "-9529994156-export declare class A {\r\n}\r\n" + }, + "./b.ts": { + "version": "-17186364832-import {A} from 'a';\nexport const b = new A();", + "signature": "-9520743082-import { A } from 'a';\r\nexport declare const b: A;\r\n" + } + }, + "options": { + "composite": true, + "moduleResolution": 1, + "listFiles": true, + "configFilePath": "./tsconfig.b.json" + }, + "referencedMap": { + "./b.ts": [ + "./a.d.ts" + ] + }, + "exportedModulesMap": { + "./b.ts": [ + "./a.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../lib/lib.d.ts", + "./a.ts", + "./b.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/transitiveReferences/initial-build/builds-correctly.js b/tests/baselines/reference/tsbuild/transitiveReferences/initial-build/builds-correctly.js new file mode 100644 index 00000000000..14ed47ea4c8 --- /dev/null +++ b/tests/baselines/reference/tsbuild/transitiveReferences/initial-build/builds-correctly.js @@ -0,0 +1,127 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig.c.json --listFiles +/lib/lib.d.ts +/src/a.ts +/lib/lib.d.ts +/src/a.d.ts +/src/b.ts +/lib/lib.d.ts +/src/a.d.ts +/src/b.d.ts +/src/refs/a.d.ts +/src/c.ts +exitCode:: ExitStatus.Success + + +//// [/src/a.d.ts] +export declare class A { +} + + +//// [/src/a.js] +"use strict"; +exports.__esModule = true; +var A = /** @class */ (function () { + function A() { + } + return A; +}()); +exports.A = A; + + +//// [/src/b.d.ts] +import { A } from '@ref/a'; +export declare const b: A; + + +//// [/src/b.js] +"use strict"; +exports.__esModule = true; +var a_1 = require("@ref/a"); +exports.b = new a_1.A(); + + +//// [/src/c.js] +"use strict"; +exports.__esModule = true; +var b_1 = require("./b"); +var a_1 = require("@ref/a"); +b_1.b; +a_1.X; + + +//// [/src/tsconfig.a.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./a.ts": { + "version": "-8566332115-export class A {}\r\n", + "signature": "-9529994156-export declare class A {\r\n}\r\n" + } + }, + "options": { + "composite": true, + "listFiles": true, + "configFilePath": "./tsconfig.a.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../lib/lib.d.ts", + "./a.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tsconfig.b.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./a.ts": { + "version": "-9529994156-export declare class A {\r\n}\r\n", + "signature": "-9529994156-export declare class A {\r\n}\r\n" + }, + "./b.ts": { + "version": "-13104686224-import {A} from '@ref/a';\r\nexport const b = new A();\r\n", + "signature": "-10067914302-import { A } from '@ref/a';\r\nexport declare const b: A;\r\n" + } + }, + "options": { + "composite": true, + "baseUrl": "./", + "paths": { + "@ref/*": [ + "./*" + ] + }, + "listFiles": true, + "configFilePath": "./tsconfig.b.json" + }, + "referencedMap": { + "./b.ts": [ + "./a.d.ts" + ] + }, + "exportedModulesMap": { + "./b.ts": [ + "./a.d.ts" + ] + }, + "semanticDiagnosticsPerFile": [ + "../lib/lib.d.ts", + "./a.ts", + "./b.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsbuild/transitiveReferences/initial-build/reports-error-about-module-not-found-with-node-resolution-with-external-module-name.js b/tests/baselines/reference/tsbuild/transitiveReferences/initial-build/reports-error-about-module-not-found-with-node-resolution-with-external-module-name.js new file mode 100644 index 00000000000..132a07d1faf --- /dev/null +++ b/tests/baselines/reference/tsbuild/transitiveReferences/initial-build/reports-error-about-module-not-found-with-node-resolution-with-external-module-name.js @@ -0,0 +1,61 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --b /src/tsconfig.c.json --listFiles +/lib/lib.d.ts +/src/a.ts +src/b.ts(1,17): error TS2307: Cannot find module 'a'. +/lib/lib.d.ts +/src/b.ts +exitCode:: ExitStatus.DiagnosticsPresent_OutputsGenerated + + +//// [/src/a.d.ts] +export declare class A { +} + + +//// [/src/a.js] +"use strict"; +exports.__esModule = true; +var A = /** @class */ (function () { + function A() { + } + return A; +}()); +exports.A = A; + + +//// [/src/b.ts] +import {A} from 'a'; +export const b = new A(); + +//// [/src/tsconfig.a.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./a.ts": { + "version": "-8566332115-export class A {}\r\n", + "signature": "-9529994156-export declare class A {\r\n}\r\n" + } + }, + "options": { + "composite": true, + "listFiles": true, + "configFilePath": "./tsconfig.a.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../lib/lib.d.ts", + "./a.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/tsconfig.b.json] +{"compilerOptions":{"composite":true,"moduleResolution":"node"},"files":["b.ts"],"references":[{"path":"tsconfig.a.json"}]} + diff --git a/tests/baselines/reference/tsc/declarationEmit/initial-build/when-pkg-references-sibling-package-through-indirect-symlink.js b/tests/baselines/reference/tsc/declarationEmit/initial-build/when-pkg-references-sibling-package-through-indirect-symlink.js index 42cb6cf78c8..4e98729a388 100644 --- a/tests/baselines/reference/tsc/declarationEmit/initial-build/when-pkg-references-sibling-package-through-indirect-symlink.js +++ b/tests/baselines/reference/tsc/declarationEmit/initial-build/when-pkg-references-sibling-package-through-indirect-symlink.js @@ -8,7 +8,7 @@ src/pkg3/src/keys.ts(2,14): error TS2742: The inferred type of 'ADMIN' cannot be /src/pkg3/node_modules/@raymondfeng/pkg2/dist/index.d.ts /src/pkg3/src/keys.ts /src/pkg3/src/index.ts -exitCode:: 1 +exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped //// [/src/pkg3/dist/index.d.ts] diff --git a/tests/baselines/reference/tsc/declarationEmit/initial-build/when-same-version-is-referenced-through-source-and-another-symlinked-package.js b/tests/baselines/reference/tsc/declarationEmit/initial-build/when-same-version-is-referenced-through-source-and-another-symlinked-package.js index a0737ae1203..e634d99e523 100644 --- a/tests/baselines/reference/tsc/declarationEmit/initial-build/when-same-version-is-referenced-through-source-and-another-symlinked-package.js +++ b/tests/baselines/reference/tsc/declarationEmit/initial-build/when-same-version-is-referenced-through-source-and-another-symlinked-package.js @@ -6,7 +6,7 @@ /src/plugin-one/node_modules/plugin-two/node_modules/typescript-fsa/index.d.ts /src/plugin-one/node_modules/plugin-two/index.d.ts /src/plugin-one/index.ts -exitCode:: 0 +exitCode:: ExitStatus.Success //// [/src/plugin-one/action.d.ts] diff --git a/tests/baselines/reference/tsc/incremental/incremental-declaration-doesnt-change/with-only-dts-files.js b/tests/baselines/reference/tsc/incremental/incremental-declaration-doesnt-change/with-only-dts-files.js new file mode 100644 index 00000000000..20fbf3472cf --- /dev/null +++ b/tests/baselines/reference/tsc/incremental/incremental-declaration-doesnt-change/with-only-dts-files.js @@ -0,0 +1,41 @@ +//// [/lib/incremental-declaration-doesnt-changeOutput.txt] +/lib/tsc --incremental --p src/project +exitCode:: ExitStatus.Success + + +//// [/src/project/src/main.d.ts] +export const x = 10;export const xy = 100; + +//// [/src/project/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./src/another.d.ts": { + "version": "-13729955264-export const y = 10;", + "signature": "-13729955264-export const y = 10;" + }, + "./src/main.d.ts": { + "version": "-10808461502-export const x = 10;export const xy = 100;", + "signature": "-10808461502-export const x = 10;export const xy = 100;" + } + }, + "options": { + "incremental": true, + "project": "./", + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./src/another.d.ts", + "./src/main.d.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsc/incremental/initial-build/when-passing-filename-for-buildinfo-on-commandline.js b/tests/baselines/reference/tsc/incremental/initial-build/when-passing-filename-for-buildinfo-on-commandline.js new file mode 100644 index 00000000000..b7b2d955768 --- /dev/null +++ b/tests/baselines/reference/tsc/incremental/initial-build/when-passing-filename-for-buildinfo-on-commandline.js @@ -0,0 +1,42 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --incremental --p src/project --tsBuildInfoFile src/project/.tsbuildinfo +exitCode:: ExitStatus.Success + + +//// [/src/project/.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./src/main.ts": { + "version": "-10726455937-export const x = 10;", + "signature": "-6057683066-export declare const x = 10;\r\n" + } + }, + "options": { + "target": 1, + "module": 1, + "incremental": true, + "project": "./", + "tsBuildInfoFile": "./.tsbuildinfo", + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./src/main.ts" + ] + }, + "version": "FakeTSVersion" +} + +//// [/src/project/src/main.js] +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.x = 10; + + diff --git a/tests/baselines/reference/tsc/incremental/initial-build/when-passing-rootDir-from-commandline.js b/tests/baselines/reference/tsc/incremental/initial-build/when-passing-rootDir-from-commandline.js new file mode 100644 index 00000000000..6c1bdf45329 --- /dev/null +++ b/tests/baselines/reference/tsc/incremental/initial-build/when-passing-rootDir-from-commandline.js @@ -0,0 +1,41 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --p src/project --rootDir src/project/src +exitCode:: ExitStatus.Success + + +//// [/src/project/dist/main.js] +"use strict"; +exports.__esModule = true; +exports.x = 10; + + +//// [/src/project/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./src/main.ts": { + "version": "-10726455937-export const x = 10;", + "signature": "-6057683066-export declare const x = 10;\r\n" + } + }, + "options": { + "incremental": true, + "outDir": "./dist", + "project": "./", + "rootDir": "./src", + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./src/main.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsc/incremental/initial-build/when-passing-rootDir-is-in-the-tsconfig.js b/tests/baselines/reference/tsc/incremental/initial-build/when-passing-rootDir-is-in-the-tsconfig.js new file mode 100644 index 00000000000..a8d320664bb --- /dev/null +++ b/tests/baselines/reference/tsc/incremental/initial-build/when-passing-rootDir-is-in-the-tsconfig.js @@ -0,0 +1,41 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --p src/project +exitCode:: ExitStatus.Success + + +//// [/src/project/built/src/main.js] +"use strict"; +exports.__esModule = true; +exports.x = 10; + + +//// [/src/project/built/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "../src/main.ts": { + "version": "-10726455937-export const x = 10;", + "signature": "-6057683066-export declare const x = 10;\r\n" + } + }, + "options": { + "incremental": true, + "outDir": "./", + "rootDir": "..", + "project": "..", + "configFilePath": "../tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../../lib/lib.d.ts", + "../src/main.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsc/incremental/initial-build/with-only-dts-files.js b/tests/baselines/reference/tsc/incremental/initial-build/with-only-dts-files.js new file mode 100644 index 00000000000..1f6070bb39f --- /dev/null +++ b/tests/baselines/reference/tsc/incremental/initial-build/with-only-dts-files.js @@ -0,0 +1,38 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc --incremental --p src/project +exitCode:: ExitStatus.Success + + +//// [/src/project/tsconfig.tsbuildinfo] +{ + "program": { + "fileInfos": { + "../../lib/lib.d.ts": { + "version": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };", + "signature": "3858781397-/// \ninterface Boolean {}\ninterface Function {}\ninterface CallableFunction {}\ninterface NewableFunction {}\ninterface IArguments {}\ninterface Number { toExponential: any; }\ninterface Object {}\ninterface RegExp {}\ninterface String { charAt: any; }\ninterface Array { length: number; [n: number]: T; }\ninterface ReadonlyArray {}\ndeclare const console: { log(msg: any): void; };" + }, + "./src/another.d.ts": { + "version": "-13729955264-export const y = 10;", + "signature": "-13729955264-export const y = 10;" + }, + "./src/main.d.ts": { + "version": "-10726455937-export const x = 10;", + "signature": "-10726455937-export const x = 10;" + } + }, + "options": { + "incremental": true, + "project": "./", + "configFilePath": "./tsconfig.json" + }, + "referencedMap": {}, + "exportedModulesMap": {}, + "semanticDiagnosticsPerFile": [ + "../../lib/lib.d.ts", + "./src/another.d.ts", + "./src/main.d.ts" + ] + }, + "version": "FakeTSVersion" +} + diff --git a/tests/baselines/reference/tsc/incremental/no-change-run/when-passing-filename-for-buildinfo-on-commandline.js b/tests/baselines/reference/tsc/incremental/no-change-run/when-passing-filename-for-buildinfo-on-commandline.js new file mode 100644 index 00000000000..b8bd5ebd76a --- /dev/null +++ b/tests/baselines/reference/tsc/incremental/no-change-run/when-passing-filename-for-buildinfo-on-commandline.js @@ -0,0 +1,5 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --incremental --p src/project --tsBuildInfoFile src/project/.tsbuildinfo +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsc/incremental/no-change-run/when-passing-rootDir-from-commandline.js b/tests/baselines/reference/tsc/incremental/no-change-run/when-passing-rootDir-from-commandline.js new file mode 100644 index 00000000000..8c858da7594 --- /dev/null +++ b/tests/baselines/reference/tsc/incremental/no-change-run/when-passing-rootDir-from-commandline.js @@ -0,0 +1,5 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --p src/project --rootDir src/project/src +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsc/incremental/no-change-run/when-passing-rootDir-is-in-the-tsconfig.js b/tests/baselines/reference/tsc/incremental/no-change-run/when-passing-rootDir-is-in-the-tsconfig.js new file mode 100644 index 00000000000..6dd851d6f1f --- /dev/null +++ b/tests/baselines/reference/tsc/incremental/no-change-run/when-passing-rootDir-is-in-the-tsconfig.js @@ -0,0 +1,5 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --p src/project +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsc/incremental/no-change-run/with-only-dts-files.js b/tests/baselines/reference/tsc/incremental/no-change-run/with-only-dts-files.js new file mode 100644 index 00000000000..c85dc67540d --- /dev/null +++ b/tests/baselines/reference/tsc/incremental/no-change-run/with-only-dts-files.js @@ -0,0 +1,5 @@ +//// [/lib/no-change-runOutput.txt] +/lib/tsc --incremental --p src/project +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/tsc/listFilesOnly/initial-build/combined-with-watch.js b/tests/baselines/reference/tsc/listFilesOnly/initial-build/combined-with-watch.js new file mode 100644 index 00000000000..7ef3574626b --- /dev/null +++ b/tests/baselines/reference/tsc/listFilesOnly/initial-build/combined-with-watch.js @@ -0,0 +1,6 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc /src/test.ts --watch --listFilesOnly +error TS6370: Options 'watch' and 'listFilesOnly' cannot be combined. +exitCode:: ExitStatus.DiagnosticsPresent_OutputsSkipped + + diff --git a/tests/baselines/reference/tsc/listFilesOnly/initial-build/loose-file.js b/tests/baselines/reference/tsc/listFilesOnly/initial-build/loose-file.js new file mode 100644 index 00000000000..6a97401e560 --- /dev/null +++ b/tests/baselines/reference/tsc/listFilesOnly/initial-build/loose-file.js @@ -0,0 +1,7 @@ +//// [/lib/initial-buildOutput.txt] +/lib/tsc /src/test.ts --listFilesOnly +/lib/lib.d.ts +/src/test.ts +exitCode:: ExitStatus.Success + + diff --git a/tests/baselines/reference/unionAndIntersectionInference3.js b/tests/baselines/reference/unionAndIntersectionInference3.js index 415d98220a5..12ce5a9a19b 100644 --- a/tests/baselines/reference/unionAndIntersectionInference3.js +++ b/tests/baselines/reference/unionAndIntersectionInference3.js @@ -52,10 +52,43 @@ let y1 = foo1(sx); // string let x2 = foo2(sa); // unknown let y2 = foo2(sx); // { extra: number } + +// Repro from #33490 + +declare class Component

{ props: P } + +export type ComponentClass

= new (props: P) => Component

; +export type FunctionComponent

= (props: P) => null; + +export type ComponentType

= FunctionComponent

| ComponentClass

; + +export interface RouteComponentProps { route: string } + +declare function withRouter< + P extends RouteComponentProps, + C extends ComponentType

+>( + component: C & ComponentType

+): ComponentClass>; + +interface Props extends RouteComponentProps { username: string } + +declare const MyComponent: ComponentType; + +withRouter(MyComponent); + +// Repro from #33490 + +type AB = { a: T } | { b: T }; + +// T & AB normalizes to T & { a: U } | T & { b: U } below +declare function foo(obj: T & AB): [T, U]; +declare let ab: AB; + +let z = foo(ab); // [AB, string] //// [unionAndIntersectionInference3.js] -"use strict"; // Repro from #30720 concatMaybe([1, 2, 3], 4); // Repros from #32247 @@ -70,3 +103,5 @@ let x1 = foo1(sa); // string let y1 = foo1(sx); // string let x2 = foo2(sa); // unknown let y2 = foo2(sx); // { extra: number } +withRouter(MyComponent); +let z = foo(ab); // [AB, string] diff --git a/tests/baselines/reference/unionAndIntersectionInference3.symbols b/tests/baselines/reference/unionAndIntersectionInference3.symbols index 1d237951b4f..43079f9e8a9 100644 --- a/tests/baselines/reference/unionAndIntersectionInference3.symbols +++ b/tests/baselines/reference/unionAndIntersectionInference3.symbols @@ -205,3 +205,107 @@ let y2 = foo2(sx); // { extra: number } >foo2 : Symbol(foo2, Decl(unionAndIntersectionInference3.ts, 42, 57)) >sx : Symbol(sx, Decl(unionAndIntersectionInference3.ts, 46, 11)) +// Repro from #33490 + +declare class Component

{ props: P } +>Component : Symbol(Component, Decl(unionAndIntersectionInference3.ts, 52, 18)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 56, 24)) +>props : Symbol(Component.props, Decl(unionAndIntersectionInference3.ts, 56, 28)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 56, 24)) + +export type ComponentClass

= new (props: P) => Component

; +>ComponentClass : Symbol(ComponentClass, Decl(unionAndIntersectionInference3.ts, 56, 39)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 58, 27)) +>props : Symbol(props, Decl(unionAndIntersectionInference3.ts, 58, 37)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 58, 27)) +>Component : Symbol(Component, Decl(unionAndIntersectionInference3.ts, 52, 18)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 58, 27)) + +export type FunctionComponent

= (props: P) => null; +>FunctionComponent : Symbol(FunctionComponent, Decl(unionAndIntersectionInference3.ts, 58, 63)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 59, 30)) +>props : Symbol(props, Decl(unionAndIntersectionInference3.ts, 59, 36)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 59, 30)) + +export type ComponentType

= FunctionComponent

| ComponentClass

; +>ComponentType : Symbol(ComponentType, Decl(unionAndIntersectionInference3.ts, 59, 54)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 61, 26)) +>FunctionComponent : Symbol(FunctionComponent, Decl(unionAndIntersectionInference3.ts, 58, 63)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 61, 26)) +>ComponentClass : Symbol(ComponentClass, Decl(unionAndIntersectionInference3.ts, 56, 39)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 61, 26)) + +export interface RouteComponentProps { route: string } +>RouteComponentProps : Symbol(RouteComponentProps, Decl(unionAndIntersectionInference3.ts, 61, 72)) +>route : Symbol(RouteComponentProps.route, Decl(unionAndIntersectionInference3.ts, 63, 38)) + +declare function withRouter< +>withRouter : Symbol(withRouter, Decl(unionAndIntersectionInference3.ts, 63, 54)) + + P extends RouteComponentProps, +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 65, 28)) +>RouteComponentProps : Symbol(RouteComponentProps, Decl(unionAndIntersectionInference3.ts, 61, 72)) + + C extends ComponentType

+>C : Symbol(C, Decl(unionAndIntersectionInference3.ts, 66, 32)) +>ComponentType : Symbol(ComponentType, Decl(unionAndIntersectionInference3.ts, 59, 54)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 65, 28)) + +>( + component: C & ComponentType

+>component : Symbol(component, Decl(unionAndIntersectionInference3.ts, 68, 2)) +>C : Symbol(C, Decl(unionAndIntersectionInference3.ts, 66, 32)) +>ComponentType : Symbol(ComponentType, Decl(unionAndIntersectionInference3.ts, 59, 54)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 65, 28)) + +): ComponentClass>; +>ComponentClass : Symbol(ComponentClass, Decl(unionAndIntersectionInference3.ts, 56, 39)) +>Omit : Symbol(Omit, Decl(lib.es5.d.ts, --, --)) +>P : Symbol(P, Decl(unionAndIntersectionInference3.ts, 65, 28)) +>RouteComponentProps : Symbol(RouteComponentProps, Decl(unionAndIntersectionInference3.ts, 61, 72)) + +interface Props extends RouteComponentProps { username: string } +>Props : Symbol(Props, Decl(unionAndIntersectionInference3.ts, 70, 54)) +>RouteComponentProps : Symbol(RouteComponentProps, Decl(unionAndIntersectionInference3.ts, 61, 72)) +>username : Symbol(Props.username, Decl(unionAndIntersectionInference3.ts, 72, 45)) + +declare const MyComponent: ComponentType; +>MyComponent : Symbol(MyComponent, Decl(unionAndIntersectionInference3.ts, 74, 13)) +>ComponentType : Symbol(ComponentType, Decl(unionAndIntersectionInference3.ts, 59, 54)) +>Props : Symbol(Props, Decl(unionAndIntersectionInference3.ts, 70, 54)) + +withRouter(MyComponent); +>withRouter : Symbol(withRouter, Decl(unionAndIntersectionInference3.ts, 63, 54)) +>MyComponent : Symbol(MyComponent, Decl(unionAndIntersectionInference3.ts, 74, 13)) + +// Repro from #33490 + +type AB = { a: T } | { b: T }; +>AB : Symbol(AB, Decl(unionAndIntersectionInference3.ts, 76, 24)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 80, 8)) +>a : Symbol(a, Decl(unionAndIntersectionInference3.ts, 80, 14)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 80, 8)) +>b : Symbol(b, Decl(unionAndIntersectionInference3.ts, 80, 25)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 80, 8)) + +// T & AB normalizes to T & { a: U } | T & { b: U } below +declare function foo(obj: T & AB): [T, U]; +>foo : Symbol(foo, Decl(unionAndIntersectionInference3.ts, 80, 33)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 83, 21)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 83, 23)) +>obj : Symbol(obj, Decl(unionAndIntersectionInference3.ts, 83, 27)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 83, 21)) +>AB : Symbol(AB, Decl(unionAndIntersectionInference3.ts, 76, 24)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 83, 23)) +>T : Symbol(T, Decl(unionAndIntersectionInference3.ts, 83, 21)) +>U : Symbol(U, Decl(unionAndIntersectionInference3.ts, 83, 23)) + +declare let ab: AB; +>ab : Symbol(ab, Decl(unionAndIntersectionInference3.ts, 84, 11)) +>AB : Symbol(AB, Decl(unionAndIntersectionInference3.ts, 76, 24)) + +let z = foo(ab); // [AB, string] +>z : Symbol(z, Decl(unionAndIntersectionInference3.ts, 86, 3)) +>foo : Symbol(foo, Decl(unionAndIntersectionInference3.ts, 80, 33)) +>ab : Symbol(ab, Decl(unionAndIntersectionInference3.ts, 84, 11)) + diff --git a/tests/baselines/reference/unionAndIntersectionInference3.types b/tests/baselines/reference/unionAndIntersectionInference3.types index fb507474321..05cb9368f83 100644 --- a/tests/baselines/reference/unionAndIntersectionInference3.types +++ b/tests/baselines/reference/unionAndIntersectionInference3.types @@ -135,3 +135,67 @@ let y2 = foo2(sx); // { extra: number } >foo2 : (obj: string[] & T) => T >sx : string[] & { extra: number; } +// Repro from #33490 + +declare class Component

{ props: P } +>Component : Component

+>props : P + +export type ComponentClass

= new (props: P) => Component

; +>ComponentClass : ComponentClass

+>props : P + +export type FunctionComponent

= (props: P) => null; +>FunctionComponent : FunctionComponent

+>props : P +>null : null + +export type ComponentType

= FunctionComponent

| ComponentClass

; +>ComponentType : ComponentType

+ +export interface RouteComponentProps { route: string } +>route : string + +declare function withRouter< +>withRouter :

>(component: (C & FunctionComponent

) | (C & ComponentClass

)) => ComponentClass>> + + P extends RouteComponentProps, + C extends ComponentType

+>( + component: C & ComponentType

+>component : (C & FunctionComponent

) | (C & ComponentClass

) + +): ComponentClass>; + +interface Props extends RouteComponentProps { username: string } +>username : string + +declare const MyComponent: ComponentType; +>MyComponent : ComponentType + +withRouter(MyComponent); +>withRouter(MyComponent) : ComponentClass> +>withRouter :

>(component: (C & FunctionComponent

) | (C & ComponentClass

)) => ComponentClass>> +>MyComponent : ComponentType + +// Repro from #33490 + +type AB = { a: T } | { b: T }; +>AB : AB +>a : T +>b : T + +// T & AB normalizes to T & { a: U } | T & { b: U } below +declare function foo(obj: T & AB): [T, U]; +>foo : (obj: (T & { a: U; }) | (T & { b: U; })) => [T, U] +>obj : (T & { a: U; }) | (T & { b: U; }) + +declare let ab: AB; +>ab : AB + +let z = foo(ab); // [AB, string] +>z : [AB, string] +>foo(ab) : [AB, string] +>foo : (obj: (T & { a: U; }) | (T & { b: U; })) => [T, U] +>ab : AB + diff --git a/tests/baselines/reference/user/TypeScript-Node-Starter.log b/tests/baselines/reference/user/TypeScript-Node-Starter.log deleted file mode 100644 index 7c34008c21d..00000000000 --- a/tests/baselines/reference/user/TypeScript-Node-Starter.log +++ /dev/null @@ -1,13 +0,0 @@ -Exit Code: 1 -Standard output: -src/config/passport.ts(136,25): error TS2339: Property 'tokens' does not exist on type 'User'. -src/controllers/api.ts(22,28): error TS2339: Property 'tokens' does not exist on type 'User'. -src/controllers/api.ts(24,27): error TS2339: Property 'facebook' does not exist on type 'User'. -src/controllers/user.ts(145,28): error TS2339: Property 'id' does not exist on type 'User'. -src/controllers/user.ts(181,28): error TS2339: Property 'id' does not exist on type 'User'. -src/controllers/user.ts(197,33): error TS2339: Property 'id' does not exist on type 'User'. -src/controllers/user.ts(211,28): error TS2339: Property 'id' does not exist on type 'User'. - - - -Standard error: diff --git a/tests/baselines/reference/user/TypeScript-React-Native-Starter.log b/tests/baselines/reference/user/TypeScript-React-Native-Starter.log index 51763a2b4b8..7741454bfa0 100644 --- a/tests/baselines/reference/user/TypeScript-React-Native-Starter.log +++ b/tests/baselines/reference/user/TypeScript-React-Native-Starter.log @@ -3,7 +3,7 @@ Standard output: node_modules/@types/react-native/index.d.ts(3425,42): error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. node_modules/@types/react-native/index.d.ts(3438,42): error TS2583: Cannot find name 'Map'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. node_modules/@types/react-native/index.d.ts(8745,18): error TS2717: Subsequent property declarations must have the same type. Property 'geolocation' must be of type 'Geolocation', but here has type 'GeolocationStatic'. -node_modules/@types/react/index.d.ts(369,23): error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. +node_modules/@types/react/index.d.ts(373,23): error TS2583: Cannot find name 'Set'. Do you need to change your target library? Try changing the `lib` compiler option to es2015 or later. diff --git a/tests/baselines/reference/user/adonis-framework.log b/tests/baselines/reference/user/adonis-framework.log index 6243a7a15db..b6797d03840 100644 --- a/tests/baselines/reference/user/adonis-framework.log +++ b/tests/baselines/reference/user/adonis-framework.log @@ -20,7 +20,7 @@ node_modules/adonis-framework/src/Config/index.js(39,15): error TS2304: Cannot f node_modules/adonis-framework/src/Config/index.js(58,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Encryption/index.js(53,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Encryption/index.js(71,34): error TS2769: No overload matches this call. - Overload 1 of 4, '(data: Binary, input_encoding: undefined, output_encoding: HexBase64BinaryEncoding): string', gave the following error. + Overload 1 of 4, '(data: ArrayBufferView, input_encoding: undefined, output_encoding: HexBase64BinaryEncoding): string', gave the following error. Argument of type 'string' is not assignable to parameter of type 'undefined'. Overload 2 of 4, '(data: string, input_encoding: "utf8" | "ascii" | "binary" | undefined, output_encoding: HexBase64BinaryEncoding): string', gave the following error. Argument of type 'string' is not assignable to parameter of type '"utf8" | "ascii" | "binary" | undefined'. @@ -28,7 +28,7 @@ node_modules/adonis-framework/src/Encryption/index.js(77,50): error TS2345: Argu node_modules/adonis-framework/src/Encryption/index.js(85,23): error TS8024: JSDoc '@param' tag has name 'value', but there is no parameter with that name. node_modules/adonis-framework/src/Encryption/index.js(87,15): error TS2304: Cannot find name 'Mixed'. node_modules/adonis-framework/src/Encryption/index.js(101,21): error TS2769: No overload matches this call. - Overload 1 of 4, '(data: Binary, input_encoding: undefined, output_encoding: Utf8AsciiBinaryEncoding): string', gave the following error. + Overload 1 of 4, '(data: ArrayBufferView, input_encoding: undefined, output_encoding: Utf8AsciiBinaryEncoding): string', gave the following error. Argument of type '"base64"' is not assignable to parameter of type 'undefined'. Overload 2 of 4, '(data: string, input_encoding: "base64" | "binary" | "hex" | undefined, output_encoding: Utf8AsciiBinaryEncoding): string', gave the following error. Argument of type 'string' is not assignable to parameter of type 'Utf8AsciiBinaryEncoding'. diff --git a/tests/baselines/reference/user/async.log b/tests/baselines/reference/user/async.log index 48b0a2be1f2..33f04aa115a 100644 --- a/tests/baselines/reference/user/async.log +++ b/tests/baselines/reference/user/async.log @@ -94,6 +94,7 @@ node_modules/async/dist/async.js(622,80): error TS2339: Property 'nodeType' does node_modules/async/dist/async.js(748,84): error TS2339: Property 'nodeType' does not exist on type 'NodeModule'. node_modules/async/dist/async.js(754,49): error TS2339: Property 'process' does not exist on type 'false | Global'. Property 'process' does not exist on type 'false'. +node_modules/async/dist/async.js(810,45): error TS2554: Expected 0 arguments, but got 1. node_modules/async/dist/async.js(923,32): error TS2554: Expected 2 arguments, but got 1. node_modules/async/dist/async.js(1299,18): error TS2532: Object is possibly 'undefined'. node_modules/async/dist/async.js(1303,3): error TS2322: Type 'any[] | undefined' is not assignable to type 'any[]'. diff --git a/tests/baselines/reference/user/axios-src.log b/tests/baselines/reference/user/axios-src.log index b42bc15b488..472cb6dd8e9 100644 --- a/tests/baselines/reference/user/axios-src.log +++ b/tests/baselines/reference/user/axios-src.log @@ -5,14 +5,11 @@ lib/adapters/http.js(84,22): error TS2345: Argument of type 'string | undefined' Type 'undefined' is not assignable to type 'string'. lib/adapters/http.js(124,17): error TS2532: Object is possibly 'undefined'. lib/adapters/http.js(124,40): error TS2532: Object is possibly 'undefined'. -lib/adapters/http.js(125,17): error TS2531: Object is possibly 'null'. -lib/adapters/http.js(125,54): error TS2531: Object is possibly 'null'. -lib/adapters/http.js(125,54): error TS2532: Object is possibly 'undefined'. -lib/adapters/http.js(224,23): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. -lib/adapters/http.js(230,44): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. -lib/adapters/http.js(236,13): error TS2322: Type 'string' is not assignable to type 'Buffer'. -lib/adapters/http.js(248,40): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. -lib/adapters/http.js(277,42): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. +lib/adapters/http.js(223,23): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. +lib/adapters/http.js(229,44): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. +lib/adapters/http.js(235,13): error TS2322: Type 'string' is not assignable to type 'Buffer'. +lib/adapters/http.js(247,40): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. +lib/adapters/http.js(276,42): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. lib/adapters/xhr.js(64,7): error TS2322: Type 'null' is not assignable to type 'XMLHttpRequest'. lib/adapters/xhr.js(76,7): error TS2322: Type 'null' is not assignable to type 'XMLHttpRequest'. lib/adapters/xhr.js(83,51): error TS2345: Argument of type 'null' is not assignable to parameter of type 'string | undefined'. diff --git a/tests/baselines/reference/user/bluebird.log b/tests/baselines/reference/user/bluebird.log index 96bdf2acccb..7f91d19ebd4 100644 --- a/tests/baselines/reference/user/bluebird.log +++ b/tests/baselines/reference/user/bluebird.log @@ -1,14 +1,6 @@ Exit Code: 1 Standard output: node_modules/bluebird/js/release/assert.js(11,30): error TS2339: Property 'constructor$' does not exist on type 'Error'. -node_modules/bluebird/js/release/async.js(38,14): error TS2339: Property 'hasDevTools' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/async.js(91,11): error TS2339: Property 'hasDevTools' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/async.js(92,21): error TS2300: Duplicate identifier 'invokeLater'. -node_modules/bluebird/js/release/async.js(93,21): error TS2300: Duplicate identifier 'invoke'. -node_modules/bluebird/js/release/async.js(94,21): error TS2300: Duplicate identifier 'settlePromises'. -node_modules/bluebird/js/release/async.js(96,21): error TS2300: Duplicate identifier 'invokeLater'. -node_modules/bluebird/js/release/async.js(108,21): error TS2300: Duplicate identifier 'invoke'. -node_modules/bluebird/js/release/async.js(118,21): error TS2300: Duplicate identifier 'settlePromises'. node_modules/bluebird/js/release/bluebird.js(5,15): error TS2367: This condition will always return 'false' since the types 'PromiseConstructor' and 'typeof Promise' have no overlap. node_modules/bluebird/js/release/bluebird.js(10,10): error TS2339: Property 'noConflict' does not exist on type 'typeof Promise'. node_modules/bluebird/js/release/call_get.js(11,24): error TS2339: Property 'canEvaluate' does not exist on type 'typeof ret'. @@ -31,42 +23,47 @@ node_modules/bluebird/js/release/debuggability.js(27,31): error TS2339: Property node_modules/bluebird/js/release/debuggability.js(28,24): error TS2339: Property 'env' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/debuggability.js(30,29): error TS2339: Property 'env' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/debuggability.js(31,25): error TS2339: Property 'env' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(106,55): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(114,55): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(155,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(165,30): error TS2339: Property 'global' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(168,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'event' must be of type 'CustomEvent', but here has type 'Event'. -node_modules/bluebird/js/release/debuggability.js(169,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(174,26): error TS2339: Property 'detail' does not exist on type 'Event'. -node_modules/bluebird/js/release/debuggability.js(177,30): error TS2339: Property 'global' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(182,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(187,30): error TS2339: Property 'global' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(197,14): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(199,48): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '["multipleResolves", MultipleResolveListener]'. -node_modules/bluebird/js/release/debuggability.js(202,19): error TS2339: Property 'global' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(209,31): error TS2339: Property 'global' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(211,31): error TS2339: Property 'global' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(242,56): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. +node_modules/bluebird/js/release/debuggability.js(156,39): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(161,38): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(199,28): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(200,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(204,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(209,28): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(210,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(214,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(225,30): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(230,26): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(236,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(252,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'event' must be of type 'CustomEvent', but here has type 'Event'. +node_modules/bluebird/js/release/debuggability.js(253,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(259,26): error TS2339: Property 'detail' does not exist on type 'Event'. +node_modules/bluebird/js/release/debuggability.js(267,18): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(283,14): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(285,48): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type '["multipleResolves", MultipleResolveListener]'. +node_modules/bluebird/js/release/debuggability.js(288,19): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(295,31): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(297,31): error TS2339: Property 'global' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(328,56): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. Type 'IArguments' is missing the following properties from type 'any[]': pop, push, concat, join, and 26 more. -node_modules/bluebird/js/release/debuggability.js(274,18): error TS2339: Property 'isObject' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(338,51): error TS2554: Expected 0 arguments, but got 1. -node_modules/bluebird/js/release/debuggability.js(352,18): error TS2339: Property 'isArray' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(424,18): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(426,18): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(491,19): error TS2350: Only a void function can be called with the 'new' keyword. -node_modules/bluebird/js/release/debuggability.js(562,59): error TS2554: Expected 0 arguments, but got 1. -node_modules/bluebird/js/release/debuggability.js(601,18): error TS2339: Property 'isObject' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(648,46): error TS2554: Expected 0 arguments, but got 1. -node_modules/bluebird/js/release/debuggability.js(736,5): error TS2721: Cannot invoke an object which is possibly 'null'. -node_modules/bluebird/js/release/debuggability.js(739,6): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(754,30): error TS2339: Property 'stack' does not exist on type 'CapturedTrace'. -node_modules/bluebird/js/release/debuggability.js(760,37): error TS2339: Property 'stack' does not exist on type 'CapturedTrace'. -node_modules/bluebird/js/release/debuggability.js(799,38): error TS2339: Property 'stack' does not exist on type 'CapturedTrace'. -node_modules/bluebird/js/release/debuggability.js(804,10): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(805,10): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(879,4): error TS2554: Expected 0 arguments, but got 1. -node_modules/bluebird/js/release/debuggability.js(885,14): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/debuggability.js(890,22): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(360,18): error TS2339: Property 'isObject' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(436,51): error TS2554: Expected 0 arguments, but got 1. +node_modules/bluebird/js/release/debuggability.js(450,18): error TS2339: Property 'isArray' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(522,18): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(524,18): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(589,19): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/debuggability.js(660,59): error TS2554: Expected 0 arguments, but got 1. +node_modules/bluebird/js/release/debuggability.js(699,18): error TS2339: Property 'isObject' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(746,46): error TS2554: Expected 0 arguments, but got 1. +node_modules/bluebird/js/release/debuggability.js(834,5): error TS2721: Cannot invoke an object which is possibly 'null'. +node_modules/bluebird/js/release/debuggability.js(837,6): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(852,30): error TS2339: Property 'stack' does not exist on type 'CapturedTrace'. +node_modules/bluebird/js/release/debuggability.js(858,37): error TS2339: Property 'stack' does not exist on type 'CapturedTrace'. +node_modules/bluebird/js/release/debuggability.js(897,38): error TS2339: Property 'stack' does not exist on type 'CapturedTrace'. +node_modules/bluebird/js/release/debuggability.js(902,10): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(903,10): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(977,4): error TS2554: Expected 0 arguments, but got 1. +node_modules/bluebird/js/release/debuggability.js(983,14): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/debuggability.js(988,22): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/errors.js(5,21): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/errors.js(6,30): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/errors.js(10,49): error TS2350: Only a void function can be called with the 'new' keyword. @@ -81,32 +78,33 @@ node_modules/bluebird/js/release/generators.js(190,15): error TS2350: Only a voi node_modules/bluebird/js/release/generators.js(208,15): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/generators.js(208,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/generators.js(220,16): error TS2554: Expected 0 arguments, but got 1. -node_modules/bluebird/js/release/join.js(6,24): error TS2339: Property 'canEvaluate' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/join.js(7,21): error TS2339: Property 'tryCatch' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/join.js(8,21): error TS2339: Property 'errorObj' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/join.js(152,46): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/map.js(10,21): error TS2339: Property 'tryCatch' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/map.js(11,21): error TS2339: Property 'errorObj' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/map.js(18,50): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/map.js(27,6): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/map.js(30,10): error TS2551: Property '_init$' does not exist on type 'MappingPromiseArray'. Did you mean '_init'? -node_modules/bluebird/js/release/map.js(36,23): error TS2339: Property '_values' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(37,23): error TS2339: Property 'length' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(47,22): error TS2339: Property '_isResolved' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(57,28): error TS2339: Property '_promise' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(70,18): error TS2339: Property '_reject' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(74,58): error TS2339: Property '_promise' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(87,22): error TS2339: Property '_reject' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(90,22): error TS2339: Property '_cancel' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(96,32): error TS2339: Property '_totalResolved' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(101,18): error TS2339: Property '_resolve' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(111,23): error TS2339: Property '_values' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(113,18): error TS2339: Property '_isResolved' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(127,10): error TS2339: Property '_resolve' does not exist on type 'MappingPromiseArray'. -node_modules/bluebird/js/release/map.js(136,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/map.js(145,42): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/map.js(151,35): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/map.js(156,66): error TS2339: Property 'promise' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/join.js(5,24): error TS2339: Property 'canEvaluate' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/join.js(6,21): error TS2339: Property 'tryCatch' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/join.js(7,21): error TS2339: Property 'errorObj' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/join.js(150,42): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/map.js(9,21): error TS2339: Property 'tryCatch' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/map.js(10,21): error TS2339: Property 'errorObj' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/map.js(17,27): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/map.js(25,14): error TS2339: Property 'isArray' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/map.js(34,6): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/map.js(37,10): error TS2551: Property '_init$' does not exist on type 'MappingPromiseArray'. Did you mean '_init'? +node_modules/bluebird/js/release/map.js(43,23): error TS2339: Property '_values' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(44,23): error TS2339: Property 'length' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(54,22): error TS2339: Property '_isResolved' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(64,28): error TS2339: Property '_promise' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(77,18): error TS2339: Property '_reject' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(81,58): error TS2339: Property '_promise' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(94,22): error TS2339: Property '_reject' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(97,22): error TS2339: Property '_cancel' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(103,32): error TS2339: Property '_totalResolved' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(108,18): error TS2339: Property '_resolve' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(118,23): error TS2339: Property '_values' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(120,18): error TS2339: Property '_isResolved' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(134,10): error TS2339: Property '_resolve' does not exist on type 'MappingPromiseArray'. +node_modules/bluebird/js/release/map.js(143,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/map.js(152,42): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/map.js(158,35): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/map.js(163,66): error TS2339: Property 'promise' does not exist on type 'MappingPromiseArray'. node_modules/bluebird/js/release/method.js(5,21): error TS2339: Property 'tryCatch' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/method.js(9,76): error TS2339: Property 'classString' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/method.js(26,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. @@ -121,79 +119,86 @@ node_modules/bluebird/js/release/nodeify.js(32,19): error TS2339: Property 'caus node_modules/bluebird/js/release/promise.js(4,12): error TS2350: Only a void function can be called with the 'new' keyword. node_modules/bluebird/js/release/promise.js(7,24): error TS2339: Property 'PromiseInspection' does not exist on type 'typeof Promise'. node_modules/bluebird/js/release/promise.js(10,27): error TS2350: Only a void function can be called with the 'new' keyword. -node_modules/bluebird/js/release/promise.js(17,10): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(20,32): error TS2322: Type 'null' is not assignable to type 'Domain'. -node_modules/bluebird/js/release/promise.js(28,6): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(58,21): error TS2339: Property 'errorObj' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(59,21): error TS2339: Property 'tryCatch' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(62,15): error TS2350: Only a void function can be called with the 'new' keyword. -node_modules/bluebird/js/release/promise.js(65,15): error TS2350: Only a void function can be called with the 'new' keyword. -node_modules/bluebird/js/release/promise.js(65,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(95,22): error TS2339: Property 'isObject' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(99,59): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(106,19): error TS2350: Only a void function can be called with the 'new' keyword. -node_modules/bluebird/js/release/promise.js(107,60): error TS2554: Expected 0 arguments, but got 1. -node_modules/bluebird/js/release/promise.js(124,22): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(126,32): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(128,14): error TS2339: Property '_warn' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(141,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(153,14): error TS2551: Property 'isFulfilled' does not exist on type 'Promise'. Did you mean '_setFulfilled'? -node_modules/bluebird/js/release/promise.js(154,37): error TS2339: Property 'value' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(156,21): error TS2551: Property 'isRejected' does not exist on type 'Promise'. Did you mean '_setRejected'? -node_modules/bluebird/js/release/promise.js(157,36): error TS2339: Property 'reason' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(165,14): error TS2339: Property '_warn' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(171,29): error TS2339: Property 'originatesFromRejection' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(182,9): error TS2339: Property '_captureStackTrace' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(212,9): error TS2339: Property '_captureStackTrace' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(219,15): error TS2350: Only a void function can be called with the 'new' keyword. -node_modules/bluebird/js/release/promise.js(219,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(243,63): error TS2339: Property '_boundTo' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(246,14): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(258,20): error TS2339: Property '_unsetRejectionIsUnhandled' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(262,20): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(269,26): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(300,10): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(305,10): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(310,10): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(327,10): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(344,42): error TS2339: Property '_isBound' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(405,50): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(409,49): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(417,50): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(421,49): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(439,26): error TS2339: Property '_propagateFrom' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(459,31): error TS2339: Property '_value' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(461,30): error TS2339: Property '_reason' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(464,17): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(471,22): error TS2339: Property 'ensureErrorObject' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(475,18): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(476,14): error TS2339: Property '_warn' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(478,10): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(485,10): error TS2339: Property '_captureStackTrace' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(486,10): error TS2339: Property '_pushContext' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(488,18): error TS2339: Property '_execute' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(494,10): error TS2339: Property '_popContext' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(511,19): error TS2350: Only a void function can be called with the 'new' keyword. -node_modules/bluebird/js/release/promise.js(512,42): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(563,22): error TS2339: Property '_promiseCancelled' does not exist on type '{}'. -node_modules/bluebird/js/release/promise.js(577,23): error TS2339: Property '_isResolved' does not exist on type '{}'. -node_modules/bluebird/js/release/promise.js(579,26): error TS2339: Property '_promiseFulfilled' does not exist on type '{}'. -node_modules/bluebird/js/release/promise.js(581,26): error TS2339: Property '_promiseRejected' does not exist on type '{}'. -node_modules/bluebird/js/release/promise.js(635,14): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(647,14): error TS2339: Property '_dereferenceTrace' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(658,46): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(664,14): error TS2339: Property '_ensurePossibleRejectionHandled' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(704,10): error TS2339: Property '_clearCancellationData' does not exist on type 'Promise'. -node_modules/bluebird/js/release/promise.js(737,6): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(767,10): error TS2339: Property 'toFastProperties' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise.js(768,10): error TS2339: Property 'toFastProperties' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(15,6): error TS2339: Property 'setReflectHandler' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(33,26): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(38,20): error TS2531: Object is possibly 'null'. +node_modules/bluebird/js/release/promise.js(41,23): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(42,6): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(44,5): error TS2322: Type '() => { domain: Domain | null; async: AsyncResource; }' is not assignable to type '(() => null) | (() => { domain: Domain | null; async: null; })'. + Type '() => { domain: Domain | null; async: AsyncResource; }' is not assignable to type '() => null'. + Type '{ domain: NodeJS.Domain | null; async: AsyncResource; }' is not assignable to type 'null'. +node_modules/bluebird/js/release/promise.js(45,10): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(49,10): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(82,21): error TS2339: Property 'errorObj' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(83,21): error TS2339: Property 'tryCatch' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(86,15): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/promise.js(89,15): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/promise.js(89,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(119,22): error TS2339: Property 'isObject' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(123,59): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(130,19): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/promise.js(131,60): error TS2554: Expected 0 arguments, but got 1. +node_modules/bluebird/js/release/promise.js(148,22): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(150,32): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(152,14): error TS2339: Property '_warn' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(165,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(177,14): error TS2551: Property 'isFulfilled' does not exist on type 'Promise'. Did you mean '_setFulfilled'? +node_modules/bluebird/js/release/promise.js(178,37): error TS2339: Property 'value' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(180,21): error TS2551: Property 'isRejected' does not exist on type 'Promise'. Did you mean '_setRejected'? +node_modules/bluebird/js/release/promise.js(181,36): error TS2339: Property 'reason' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(189,14): error TS2339: Property '_warn' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(195,29): error TS2339: Property 'originatesFromRejection' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(206,9): error TS2339: Property '_captureStackTrace' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(236,9): error TS2339: Property '_captureStackTrace' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(243,15): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/promise.js(243,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(267,63): error TS2339: Property '_boundTo' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(270,14): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(282,20): error TS2339: Property '_unsetRejectionIsUnhandled' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(286,20): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(291,27): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(323,10): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(328,10): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(333,10): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(350,10): error TS2339: Property '_fireEvent' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(375,42): error TS2339: Property '_isBound' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(435,46): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(438,44): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(446,22): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(450,22): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(468,26): error TS2339: Property '_propagateFrom' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(489,31): error TS2339: Property '_value' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(491,30): error TS2339: Property '_reason' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(494,17): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(501,22): error TS2339: Property 'ensureErrorObject' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(505,18): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(506,14): error TS2339: Property '_warn' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(508,10): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(515,10): error TS2339: Property '_captureStackTrace' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(516,10): error TS2339: Property '_pushContext' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(518,18): error TS2339: Property '_execute' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(524,10): error TS2339: Property '_popContext' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(541,19): error TS2350: Only a void function can be called with the 'new' keyword. +node_modules/bluebird/js/release/promise.js(542,42): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(593,22): error TS2339: Property '_promiseCancelled' does not exist on type '{}'. +node_modules/bluebird/js/release/promise.js(607,23): error TS2339: Property '_isResolved' does not exist on type '{}'. +node_modules/bluebird/js/release/promise.js(609,26): error TS2339: Property '_promiseFulfilled' does not exist on type '{}'. +node_modules/bluebird/js/release/promise.js(611,26): error TS2339: Property '_promiseRejected' does not exist on type '{}'. +node_modules/bluebird/js/release/promise.js(665,14): error TS2339: Property '_attachExtraTrace' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(677,14): error TS2339: Property '_dereferenceTrace' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(688,46): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(694,14): error TS2339: Property '_ensurePossibleRejectionHandled' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(734,10): error TS2339: Property '_clearCancellationData' does not exist on type 'Promise'. +node_modules/bluebird/js/release/promise.js(767,6): error TS2339: Property 'notEnumerableProp' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(797,10): error TS2339: Property 'toFastProperties' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise.js(798,10): error TS2339: Property 'toFastProperties' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/promise_array.js(5,20): error TS2339: Property 'isArray' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise_array.js(26,6): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise_array.js(61,19): error TS2339: Property 'asArray' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise_array.js(64,72): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/promise_array.js(71,18): error TS2339: Property '_resolveEmptyArray' does not exist on type 'PromiseArray'. -node_modules/bluebird/js/release/promise_array.js(109,76): error TS2554: Expected 0-1 arguments, but got 2. -node_modules/bluebird/js/release/promise_array.js(111,53): error TS2554: Expected 0 arguments, but got 1. +node_modules/bluebird/js/release/promise_array.js(27,6): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise_array.js(62,19): error TS2339: Property 'asArray' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise_array.js(65,72): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/promise_array.js(72,18): error TS2339: Property '_resolveEmptyArray' does not exist on type 'PromiseArray'. +node_modules/bluebird/js/release/promise_array.js(110,76): error TS2554: Expected 0-1 arguments, but got 2. +node_modules/bluebird/js/release/promise_array.js(112,53): error TS2554: Expected 0 arguments, but got 1. node_modules/bluebird/js/release/promisify.js(6,25): error TS2339: Property 'withAppended' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/promisify.js(7,29): error TS2339: Property 'maybeWrapAsError' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/promisify.js(8,24): error TS2339: Property 'canEvaluate' does not exist on type 'typeof ret'. @@ -235,16 +240,16 @@ node_modules/bluebird/js/release/props.js(78,14): error TS2339: Property '_resol node_modules/bluebird/js/release/props.js(102,53): error TS2339: Property 'promise' does not exist on type 'PropertiesPromiseArray'. node_modules/bluebird/js/release/race.js(18,25): error TS2339: Property 'asArray' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/race.js(20,92): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/reduce.js(10,21): error TS2339: Property 'tryCatch' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/reduce.js(15,44): error TS2339: Property 'domainBind' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/reduce.js(32,6): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/reduce.js(44,9): error TS2532: Object is possibly 'undefined'. -node_modules/bluebird/js/release/reduce.js(61,10): error TS2339: Property '_promise' does not exist on type 'ReductionPromiseArray'. -node_modules/bluebird/js/release/reduce.js(66,52): error TS2339: Property '_cancel' does not exist on type 'ReductionPromiseArray'. -node_modules/bluebird/js/release/reduce.js(67,14): error TS2339: Property '_isResolved' does not exist on type 'ReductionPromiseArray'. -node_modules/bluebird/js/release/reduce.js(68,10): error TS2551: Property '_resultCancelled$' does not exist on type 'ReductionPromiseArray'. Did you mean '_resultCancelled'? -node_modules/bluebird/js/release/reduce.js(130,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/reduce.js(133,18): error TS2339: Property 'promise' does not exist on type 'ReductionPromiseArray'. +node_modules/bluebird/js/release/reduce.js(9,21): error TS2339: Property 'tryCatch' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/reduce.js(14,21): error TS2339: Property 'contextBind' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/reduce.js(31,6): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/reduce.js(43,9): error TS2532: Object is possibly 'undefined'. +node_modules/bluebird/js/release/reduce.js(60,10): error TS2339: Property '_promise' does not exist on type 'ReductionPromiseArray'. +node_modules/bluebird/js/release/reduce.js(65,52): error TS2339: Property '_cancel' does not exist on type 'ReductionPromiseArray'. +node_modules/bluebird/js/release/reduce.js(66,14): error TS2339: Property '_isResolved' does not exist on type 'ReductionPromiseArray'. +node_modules/bluebird/js/release/reduce.js(67,10): error TS2551: Property '_resultCancelled$' does not exist on type 'ReductionPromiseArray'. Did you mean '_resultCancelled'? +node_modules/bluebird/js/release/reduce.js(141,68): error TS2339: Property 'classString' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/reduce.js(144,18): error TS2339: Property 'promise' does not exist on type 'ReductionPromiseArray'. node_modules/bluebird/js/release/schedule.js(7,26): error TS2339: Property 'getNativePromise' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/schedule.js(8,10): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/schedule.js(23,31): error TS2339: Property 'standalone' does not exist on type 'Navigator'. @@ -256,6 +261,7 @@ node_modules/bluebird/js/release/settle.js(15,31): error TS2339: Property '_leng node_modules/bluebird/js/release/settle.js(16,14): error TS2339: Property '_resolve' does not exist on type 'SettledPromiseArray'. node_modules/bluebird/js/release/settle.js(16,28): error TS2339: Property '_values' does not exist on type 'SettledPromiseArray'. node_modules/bluebird/js/release/settle.js(37,46): error TS2339: Property 'promise' does not exist on type 'SettledPromiseArray'. +node_modules/bluebird/js/release/settle.js(41,46): error TS2339: Property 'promise' does not exist on type 'SettledPromiseArray'. node_modules/bluebird/js/release/some.js(7,20): error TS2339: Property 'isArray' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/some.js(17,6): error TS2339: Property 'inherits' does not exist on type 'typeof ret'. node_modules/bluebird/js/release/some.js(24,14): error TS2339: Property '_resolve' does not exist on type 'SomePromiseArray'. @@ -302,17 +308,15 @@ node_modules/bluebird/js/release/using.js(223,15): error TS2350: Only a void fun node_modules/bluebird/js/release/util.js(279,45): error TS2345: Argument of type 'PropertyDescriptor | { value: any; } | undefined' is not assignable to parameter of type 'PropertyDescriptor & ThisType'. Type 'undefined' is not assignable to type 'PropertyDescriptor & ThisType'. Type 'undefined' is not assignable to type 'PropertyDescriptor'. -node_modules/bluebird/js/release/util.js(341,5): error TS2322: Type '{ isClass: (fn: any) => boolean; isIdentifier: (str: any) => boolean; inheritedDataKeys: (obj: any) => string[]; getDataPropertyOrDefault: (obj: any, key: any, defaultValue: any) => any; ... 28 more ...; domainBind: (self: any, cb: any) => any; }' is not assignable to type 'typeof ret'. - Object literal may only specify known properties, and 'isClass' does not exist in type 'typeof ret'. -node_modules/bluebird/js/release/util.js(367,25): error TS2304: Cannot find name 'chrome'. -node_modules/bluebird/js/release/util.js(367,51): error TS2304: Cannot find name 'chrome'. -node_modules/bluebird/js/release/util.js(368,25): error TS2304: Cannot find name 'chrome'. -node_modules/bluebird/js/release/util.js(376,24): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/util.js(383,13): error TS2532: Object is possibly 'undefined'. -node_modules/bluebird/js/release/util.js(383,33): error TS2532: Object is possibly 'undefined'. -node_modules/bluebird/js/release/util.js(383,54): error TS2532: Object is possibly 'undefined'. -node_modules/bluebird/js/release/util.js(386,9): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. -node_modules/bluebird/js/release/util.js(386,21): error TS2339: Property 'toFastProperties' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/util.js(362,5): error TS2322: Type '{ setReflectHandler: (fn: any) => void; isClass: (fn: any) => boolean; isIdentifier: (str: any) => boolean; inheritedDataKeys: (obj: any) => string[]; getDataPropertyOrDefault: (obj: any, key: any, defaultValue: any) => any; ... 27 more ...; contextBind: (ctx: any, cb: any) => any; }' is not assignable to type 'typeof ret'. + Object literal may only specify known properties, and 'setReflectHandler' does not exist in type 'typeof ret'. +node_modules/bluebird/js/release/util.js(398,24): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/util.js(405,13): error TS2532: Object is possibly 'undefined'. +node_modules/bluebird/js/release/util.js(405,33): error TS2532: Object is possibly 'undefined'. +node_modules/bluebird/js/release/util.js(405,54): error TS2532: Object is possibly 'undefined'. +node_modules/bluebird/js/release/util.js(407,37): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/util.js(418,9): error TS2339: Property 'isNode' does not exist on type 'typeof ret'. +node_modules/bluebird/js/release/util.js(418,21): error TS2339: Property 'toFastProperties' does not exist on type 'typeof ret'. diff --git a/tests/baselines/reference/user/chrome-devtools-frontend.log b/tests/baselines/reference/user/chrome-devtools-frontend.log index 8c9e16f0139..b0dabfddafc 100644 --- a/tests/baselines/reference/user/chrome-devtools-frontend.log +++ b/tests/baselines/reference/user/chrome-devtools-frontend.log @@ -1,6 +1,6 @@ Exit Code: 1 Standard output: -../../../../built/local/lib.es5.d.ts(1421,11): error TS2300: Duplicate identifier 'ArrayLike'. +../../../../built/local/lib.es5.d.ts(1433,11): error TS2300: Duplicate identifier 'ArrayLike'. ../../../../node_modules/@types/node/globals.d.ts(234,13): error TS2403: Subsequent variable declarations must have the same type. Variable 'module' must be of type '{}', but here has type 'NodeModule'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(43,8): error TS2339: Property '_importScriptPathPrefix' does not exist on type 'Window & typeof globalThis'. node_modules/chrome-devtools-frontend/front_end/Runtime.js(77,16): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. @@ -3006,6 +3006,7 @@ node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighth node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(68409,16): error TS2339: Property 'height' does not exist on type 'constructor'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(68410,25): error TS2339: Property 'width' does not exist on type 'constructor'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(68410,39): error TS2339: Property 'height' does not exist on type 'constructor'. +node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(69550,21): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(69799,1): error TS2323: Cannot redeclare exported variable 'parse'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(70747,4): error TS2531: Object is possibly 'null'. node_modules/chrome-devtools-frontend/front_end/audits2_worker/lighthouse/lighthouse-background.js(70747,26): error TS2531: Object is possibly 'null'. @@ -3664,8 +3665,7 @@ node_modules/chrome-devtools-frontend/front_end/common/Settings.js(542,18): erro node_modules/chrome-devtools-frontend/front_end/common/Throttler.js(97,14): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. node_modules/chrome-devtools-frontend/front_end/common/Throttler.js(102,5): error TS2322: Type 'Timeout' is not assignable to type 'number'. node_modules/chrome-devtools-frontend/front_end/common/Throttler.js(113,15): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. -node_modules/chrome-devtools-frontend/front_end/common/UIString.js(32,1): error TS2322: Type 'typeof Common | {}' is not assignable to type 'typeof Common'. - Type '{}' is missing the following properties from type 'typeof Common': Object, EventTarget, Event, ParsedURL, and 39 more. +node_modules/chrome-devtools-frontend/front_end/common/UIString.js(32,1): error TS2740: Type '{}' is missing the following properties from type 'typeof Common': Object, EventTarget, Event, ParsedURL, and 39 more. node_modules/chrome-devtools-frontend/front_end/common/UIString.js(40,17): error TS2339: Property 'vsprintf' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/common/UIString.js(62,36): error TS2339: Property 'tokenizeFormatString' does not exist on type 'StringConstructor'. node_modules/chrome-devtools-frontend/front_end/common/UIString.js(62,87): error TS2339: Property 'standardFormatters' does not exist on type 'StringConstructor'. @@ -3866,10 +3866,9 @@ node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(133,9) node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(147,27): error TS2740: Type 'Element' is missing the following properties from type 'Icon': createdCallback, _descriptor, _spriteSheet, _iconType, and 117 more. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(177,67): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(179,61): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(209,41): error TS2339: Property 'asParsedURL' does not exist on type 'string'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(213,28): error TS2555: Expected at least 2 arguments, but got 1. -node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(214,31): error TS2345: Argument of type '{ key: any; text: string; negative: false; }' is not assignable to parameter of type '{ key: string; text: string; regex: RegExp; negative: boolean; }'. - Property 'regex' is missing in type '{ key: any; text: string; negative: false; }' but required in type '{ key: string; text: string; regex: RegExp; negative: boolean; }'. +node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(214,31): error TS2345: Argument of type '{ key: any; text: any; negative: false; }' is not assignable to parameter of type '{ key: string; text: string; regex: RegExp; negative: boolean; }'. + Property 'regex' is missing in type '{ key: any; text: any; negative: false; }' but required in type '{ key: string; text: string; regex: RegExp; negative: boolean; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(214,45): error TS2339: Property 'ConsoleFilter' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(216,25): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. node_modules/chrome-devtools-frontend/front_end/console/ConsoleSidebar.js(226,9): error TS2339: Property 'ConsoleSidebar' does not exist on type '{ new (): Console; prototype: Console; }'. @@ -6631,8 +6630,8 @@ node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.j node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(85,39): error TS2551: Property '_logItemCategoriesMap' does not exist on type 'typeof PaintProfilerView'. Did you mean '_initLogItemCategories'? node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(86,44): error TS2551: Property '_logItemCategoriesMap' does not exist on type 'typeof PaintProfilerView'. Did you mean '_initLogItemCategories'? node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(128,35): error TS2551: Property '_logItemCategoriesMap' does not exist on type 'typeof PaintProfilerView'. Did you mean '_initLogItemCategories'? -node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(129,5): error TS2322: Type '{}' is not assignable to type '{ [x: string]: PaintProfilerCategory; }'. - Index signature is missing in type '{}'. +node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(129,5): error TS2322: Type '{ 'Clear': PaintProfilerCategory; 'DrawPaint': PaintProfilerCategory; 'DrawData': PaintProfilerCategory; 'SetMatrix': PaintProfilerCategory; ... 31 more ...; 'DrawTextOnPath': PaintProfilerCategory; }' is not assignable to type '{ [x: string]: PaintProfilerCategory; }'. + Index signature is missing in type '{ 'Clear': PaintProfilerCategory; 'DrawPaint': PaintProfilerCategory; 'DrawData': PaintProfilerCategory; 'SetMatrix': PaintProfilerCategory; ... 31 more ...; 'DrawTextOnPath': PaintProfilerCategory; }'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(158,24): error TS2694: Namespace 'Protocol' has no exported member 'DOM'. node_modules/chrome-devtools-frontend/front_end/layer_viewer/PaintProfilerView.js(244,26): error TS2345: Argument of type '{}' is not assignable to parameter of type '{ [x: string]: number; }'. Index signature is missing in type '{}'. @@ -8756,8 +8755,8 @@ node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(4 node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(42,60): error TS2555: Expected at least 2 arguments, but got 1. node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(77,18): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(114,37): error TS2339: Property 'valuesArray' does not exist on type 'Set'. -node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(124,40): error TS2345: Argument of type '{}' is not assignable to parameter of type '{ [x: string]: boolean; }'. - Index signature is missing in type '{}'. +node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(124,40): error TS2345: Argument of type '{ '0': boolean; }' is not assignable to parameter of type '{ [x: string]: boolean; }'. + Index signature is missing in type '{ '0': boolean; }'. node_modules/chrome-devtools-frontend/front_end/resources/DatabaseTableView.js(130,18): error TS2339: Property 'removeChildren' does not exist on type 'Element'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(41,12): error TS2339: Property 'registerStorageDispatcher' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/resources/IndexedDBModel.js(43,35): error TS2339: Property 'indexedDBAgent' does not exist on type 'Target'. @@ -9458,8 +9457,8 @@ node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1060,13): Type '{}' has no call signatures. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1084,19): error TS2339: Property 'networkAgent' does not exist on type 'Target'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1089,14): error TS7014: Function type, which lacks return-type annotation, implicitly has an 'any' return type. -node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1101,35): error TS2345: Argument of type '{}' is not assignable to parameter of type '{ [x: string]: string; }'. - Index signature is missing in type '{}'. +node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1101,35): error TS2345: Argument of type '{ 'User-Agent': string; 'Cache-Control': string; }' is not assignable to parameter of type '{ [x: string]: string; }'. + Index signature is missing in type '{ 'User-Agent': string; 'Cache-Control': string; }'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1115,24): error TS2694: Namespace 'Protocol' has no exported member 'NetworkAgent'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1116,24): error TS2694: Namespace 'Protocol' has no exported member 'Network'. node_modules/chrome-devtools-frontend/front_end/sdk/NetworkManager.js(1117,24): error TS2694: Namespace 'Protocol' has no exported member 'Network'. diff --git a/tests/baselines/reference/user/enhanced-resolve.log b/tests/baselines/reference/user/enhanced-resolve.log index 44f7c0712d0..79fe90add79 100644 --- a/tests/baselines/reference/user/enhanced-resolve.log +++ b/tests/baselines/reference/user/enhanced-resolve.log @@ -1,44 +1,44 @@ Exit Code: 1 Standard output: -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(116,18): error TS2769: No overload matches this call. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(127,18): error TS2769: No overload matches this call. Overload 1 of 2, '(intervalId: Timeout): void', gave the following error. Argument of type 'Timeout | null' is not assignable to parameter of type 'Timeout'. Type 'null' is not assignable to type 'Timeout'. Overload 2 of 2, '(handle?: number | undefined): void', gave the following error. Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(129,18): error TS2769: No overload matches this call. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(143,18): error TS2769: No overload matches this call. Overload 1 of 2, '(intervalId: Timeout): void', gave the following error. Argument of type 'Timeout | null' is not assignable to parameter of type 'Timeout'. Type 'null' is not assignable to type 'Timeout'. Overload 2 of 2, '(handle?: number | undefined): void', gave the following error. Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(147,18): error TS2769: No overload matches this call. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(162,18): error TS2769: No overload matches this call. Overload 1 of 2, '(intervalId: Timeout): void', gave the following error. Argument of type 'Timeout | null' is not assignable to parameter of type 'Timeout'. Type 'null' is not assignable to type 'Timeout'. Overload 2 of 2, '(handle?: number | undefined): void', gave the following error. Argument of type 'Timeout | null' is not assignable to parameter of type 'number | undefined'. Type 'null' is not assignable to type 'number | undefined'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(176,19): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(179,23): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(182,22): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(185,26): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(188,23): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(191,27): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(209,4): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(220,4): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(224,23): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. -node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(227,27): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. -node_modules/enhanced-resolve/lib/Resolver.js(165,17): error TS2339: Property 'push' does not exist on type 'Set'. -node_modules/enhanced-resolve/lib/Resolver.js(181,11): error TS2339: Property 'details' does not exist on type 'Error'. -node_modules/enhanced-resolve/lib/Resolver.js(182,11): error TS2339: Property 'missing' does not exist on type 'Error'. -node_modules/enhanced-resolve/lib/Resolver.js(219,20): error TS2339: Property 'recursion' does not exist on type 'Error'. -node_modules/enhanced-resolve/lib/concord.js(75,30): error TS2531: Object is possibly 'null'. -node_modules/enhanced-resolve/lib/concord.js(76,17): error TS2531: Object is possibly 'null'. -node_modules/enhanced-resolve/lib/createInnerCallback.js(17,20): error TS2339: Property 'stack' does not exist on type '(...args: any[]) => any'. -node_modules/enhanced-resolve/lib/createInnerCallback.js(18,20): error TS2339: Property 'missing' does not exist on type '(...args: any[]) => any'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(192,20): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(197,24): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(202,23): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(207,27): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(212,24): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(217,28): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(235,4): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(246,4): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(252,24): error TS2322: Type 'null' is not assignable to type '(path: any, callback: any) => void'. +node_modules/enhanced-resolve/lib/CachedInputFileSystem.js(257,28): error TS2322: Type 'null' is not assignable to type '(path: any) => any'. +node_modules/enhanced-resolve/lib/Resolver.js(189,18): error TS2339: Property 'push' does not exist on type 'Set'. +node_modules/enhanced-resolve/lib/Resolver.js(210,13): error TS2339: Property 'details' does not exist on type 'Error'. +node_modules/enhanced-resolve/lib/Resolver.js(211,13): error TS2339: Property 'missing' does not exist on type 'Error'. +node_modules/enhanced-resolve/lib/Resolver.js(262,20): error TS2339: Property 'recursion' does not exist on type 'Error'. +node_modules/enhanced-resolve/lib/concord.js(80,30): error TS2531: Object is possibly 'null'. +node_modules/enhanced-resolve/lib/concord.js(81,17): error TS2531: Object is possibly 'null'. +node_modules/enhanced-resolve/lib/createInnerCallback.js(22,20): error TS2339: Property 'stack' does not exist on type '(...args: any[]) => any'. +node_modules/enhanced-resolve/lib/createInnerCallback.js(23,20): error TS2339: Property 'missing' does not exist on type '(...args: any[]) => any'. diff --git a/tests/baselines/reference/user/lodash.log b/tests/baselines/reference/user/lodash.log index db27283048e..365222ccaca 100644 --- a/tests/baselines/reference/user/lodash.log +++ b/tests/baselines/reference/user/lodash.log @@ -246,6 +246,7 @@ node_modules/lodash/core.js(3424,41): error TS2769: No overload matches this cal node_modules/lodash/core.js(3573,51): error TS2532: Object is possibly 'undefined'. node_modules/lodash/core.js(3590,63): error TS2345: Argument of type 'IArguments' is not assignable to parameter of type 'any[]'. Type 'IArguments' is missing the following properties from type 'any[]': pop, push, concat, join, and 26 more. +node_modules/lodash/core.js(3814,33): error TS2339: Property '__chain__' does not exist on type 'lodash'. node_modules/lodash/core.js(3830,14): error TS2304: Cannot find name 'define'. node_modules/lodash/core.js(3830,45): error TS2304: Cannot find name 'define'. node_modules/lodash/core.js(3830,71): error TS2304: Cannot find name 'define'. diff --git a/tests/baselines/reference/user/npm.log b/tests/baselines/reference/user/npm.log index 07ac8d7d8a6..bdf514c4072 100644 --- a/tests/baselines/reference/user/npm.log +++ b/tests/baselines/reference/user/npm.log @@ -723,7 +723,6 @@ node_modules/npm/lib/search/all-package-metadata.js(239,20): error TS2339: Prope node_modules/npm/lib/search/esearch.js(15,36): error TS2339: Property 'config' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/search/esearch.js(35,7): error TS2339: Property 'registry' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/search/format-package-stream.js(130,31): error TS2339: Property 'fd' does not exist on type 'WriteStream'. -node_modules/npm/lib/search/format-package-stream.js(130,63): error TS2339: Property 'getWindowSize' does not exist on type 'WriteStream'. node_modules/npm/lib/set.js(8,22): error TS2339: Property 'commands' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/set.js(12,7): error TS2339: Property 'commands' does not exist on type 'typeof EventEmitter'. node_modules/npm/lib/shrinkwrap.js(30,29): error TS2339: Property 'lockfileVersion' does not exist on type 'typeof EventEmitter'. diff --git a/tests/baselines/reference/user/npmlog.log b/tests/baselines/reference/user/npmlog.log index 6b6e315d996..6847693c109 100644 --- a/tests/baselines/reference/user/npmlog.log +++ b/tests/baselines/reference/user/npmlog.log @@ -8,12 +8,12 @@ node_modules/npmlog/log.js(194,37): error TS2345: Argument of type 'any[]' is no Property '0' is missing in type 'any[]' but required in type '[any, ...any[]]'. node_modules/npmlog/log.js(218,12): error TS2551: Property '_paused' does not exist on type 'typeof EventEmitter'. Did you mean 'pause'? node_modules/npmlog/log.js(271,16): error TS2769: No overload matches this call. - Overload 1 of 2, '(buffer: string | Uint8Array, cb?: ((err?: Error | null | undefined) => void) | undefined): boolean', gave the following error. + Overload 1 of 2, '(buffer: string | Uint8Array, cb?: ((err?: Error | undefined) => void) | undefined): boolean', gave the following error. + Argument of type 'string | undefined' is not assignable to parameter of type 'string | Uint8Array'. + Type 'undefined' is not assignable to type 'string | Uint8Array'. + Overload 2 of 2, '(str: string | Uint8Array, encoding?: string | undefined, cb?: ((err?: Error | undefined) => void) | undefined): boolean', gave the following error. Argument of type 'string | undefined' is not assignable to parameter of type 'string | Uint8Array'. Type 'undefined' is not assignable to type 'string | Uint8Array'. - Overload 2 of 2, '(str: string, encoding?: string | undefined, cb?: ((err?: Error | null | undefined) => void) | undefined): boolean', gave the following error. - Argument of type 'string | undefined' is not assignable to parameter of type 'string'. - Type 'undefined' is not assignable to type 'string'. diff --git a/tests/baselines/reference/user/prettier.log b/tests/baselines/reference/user/prettier.log index c2332df2620..05342cae1e1 100644 --- a/tests/baselines/reference/user/prettier.log +++ b/tests/baselines/reference/user/prettier.log @@ -23,18 +23,17 @@ node_modules/@glimmer/util/dist/types/lib/destroy.d.ts(3,69): error TS2677: A ty Index signature is missing in type 'SymbolDestroyable'. node_modules/@glimmer/util/dist/types/lib/dom.d.ts(1,31): error TS2307: Cannot find module '@simple-dom/interface'. node_modules/@glimmer/util/dist/types/lib/is-serialization-first-node.d.ts(1,28): error TS2307: Cannot find module '@simple-dom/interface'. -src/cli/util.js(63,44): error TS2345: Argument of type 'null' is not assignable to parameter of type 'number | undefined'. -src/cli/util.js(122,38): error TS2339: Property 'sync' does not exist on type '(...args: any[]) => any'. -src/cli/util.js(416,36): error TS2345: Argument of type '{ dot: true; nodir: boolean; }' is not assignable to parameter of type 'GlobbyOptions'. +src/cli/util.js(60,44): error TS2345: Argument of type 'null' is not assignable to parameter of type 'number | undefined'. +src/cli/util.js(119,38): error TS2339: Property 'sync' does not exist on type '(...args: any[]) => any'. +src/cli/util.js(413,36): error TS2345: Argument of type '{ dot: true; nodir: boolean; }' is not assignable to parameter of type 'GlobbyOptions'. Object literal may only specify known properties, and 'nodir' does not exist in type 'GlobbyOptions'. -src/cli/util.js(483,46): error TS2345: Argument of type 'null' is not assignable to parameter of type 'number | undefined'. -src/cli/util.js(509,36): error TS2339: Property 'grey' does not exist on type 'typeof import("../../../node_modules/chalk/types/index")'. -src/cli/util.js(562,39): error TS2339: Property 'grey' does not exist on type 'typeof import("../../../node_modules/chalk/types/index")'. -src/cli/util.js(635,16): error TS2339: Property 'type' does not exist on type 'never'. -src/cli/util.js(636,16): error TS2339: Property 'oppositeDescription' does not exist on type 'never'. -src/cli/util.js(637,17): error TS2339: Property 'name' does not exist on type 'never'. -src/cli/util.js(737,22): error TS2339: Property 'name' does not exist on type 'never'. -src/cli/util.js(737,46): error TS2339: Property 'alias' does not exist on type 'never'. +src/cli/util.js(507,44): error TS2345: Argument of type 'null' is not assignable to parameter of type 'number | undefined'. +src/cli/util.js(528,37): error TS2339: Property 'grey' does not exist on type 'typeof import("/prettier/prettier/node_modules/chalk/types/index")'. +src/cli/util.js(591,16): error TS2339: Property 'type' does not exist on type 'never'. +src/cli/util.js(592,16): error TS2339: Property 'oppositeDescription' does not exist on type 'never'. +src/cli/util.js(593,17): error TS2339: Property 'name' does not exist on type 'never'. +src/cli/util.js(693,22): error TS2339: Property 'name' does not exist on type 'never'. +src/cli/util.js(693,46): error TS2339: Property 'alias' does not exist on type 'never'. src/common/create-ignorer.js(34,19): error TS2349: This expression is not callable. Type 'typeof import("/prettier/prettier/node_modules/ignore/index")' has no call signatures. src/common/parser-create-error.js(8,9): error TS2339: Property 'loc' does not exist on type 'SyntaxError'. @@ -45,7 +44,7 @@ src/config/resolve-config.js(121,32): error TS2345: Argument of type '{ sync: fa Property 'cache' is missing in type '{ sync: false; }' but required in type '{ cache: boolean; sync: boolean; }'. src/config/resolve-config.js(128,32): error TS2345: Argument of type '{ sync: true; }' is not assignable to parameter of type '{ cache: boolean; sync: boolean; }'. Property 'cache' is missing in type '{ sync: true; }' but required in type '{ cache: boolean; sync: boolean; }'. -src/doc/doc-printer.js(7,14): error TS1023: An index signature parameter type must be 'string' or 'number'. +src/doc/doc-printer.js(7,14): error TS1023: An index signature parameter type must be either 'string' or 'number'. src/doc/doc-printer.js(7,37): error TS2304: Cannot find name 'MODE'. src/doc/doc-printer.js(257,17): error TS2532: Object is possibly 'undefined'. src/doc/doc-printer.js(258,18): error TS2532: Object is possibly 'undefined'. @@ -77,6 +76,8 @@ src/language-css/utils.js(3,30): error TS2307: Cannot find module 'html-tag-name src/language-graphql/index.js(8,26): error TS2307: Cannot find module 'linguist-languages/data/GraphQL'. src/language-graphql/index.js(8,62): error TS2345: Argument of type '{ override: { since: string; parsers: string[]; vscodeLanguageIds: string[]; }; }' is not assignable to parameter of type '{ extend: any; override: any; exclude: any; }'. Type '{ override: { since: string; parsers: string[]; vscodeLanguageIds: string[]; }; }' is missing the following properties from type '{ extend: any; override: any; exclude: any; }': extend, exclude +src/language-graphql/parser-graphql.js(64,17): error TS2532: Object is possibly 'undefined'. +src/language-graphql/parser-graphql.js(65,19): error TS2532: Object is possibly 'undefined'. src/language-handlebars/index.js(7,26): error TS2307: Cannot find module 'linguist-languages/data/Handlebars'. src/language-handlebars/index.js(7,65): error TS2345: Argument of type '{ override: { since: null; parsers: string[]; vscodeLanguageIds: string[]; }; }' is not assignable to parameter of type '{ extend: any; override: any; exclude: any; }'. Type '{ override: { since: null; parsers: string[]; vscodeLanguageIds: string[]; }; }' is missing the following properties from type '{ extend: any; override: any; exclude: any; }': extend, exclude @@ -196,7 +197,7 @@ src/language-js/index.js(71,73): error TS2345: Argument of type '{ override: { s src/language-js/index.js(81,26): error TS2307: Cannot find module 'linguist-languages/data/JSON5'. src/language-js/index.js(81,60): error TS2345: Argument of type '{ override: { since: string; parsers: string[]; vscodeLanguageIds: string[]; }; }' is not assignable to parameter of type '{ extend: any; override: any; exclude: any; }'. Type '{ override: { since: string; parsers: string[]; vscodeLanguageIds: string[]; }; }' is missing the following properties from type '{ extend: any; override: any; exclude: any; }': extend, exclude -src/language-js/needs-parens.js(871,14): error TS2769: No overload matches this call. +src/language-js/needs-parens.js(880,14): error TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray<(childPath: any) => any>[]): ((childPath: any) => any)[]', gave the following error. Argument of type '(string | number)[]' is not assignable to parameter of type 'ConcatArray<(childPath: any) => any>'. The types returned by 'slice(...)' are incompatible between these types. @@ -206,60 +207,40 @@ src/language-js/needs-parens.js(871,14): error TS2769: No overload matches this Overload 2 of 2, '(...items: (((childPath: any) => any) | ConcatArray<(childPath: any) => any>)[]): ((childPath: any) => any)[]', gave the following error. Argument of type '(string | number)[]' is not assignable to parameter of type '((childPath: any) => any) | ConcatArray<(childPath: any) => any>'. Type '(string | number)[]' is not assignable to type 'ConcatArray<(childPath: any) => any>'. -src/language-js/printer-estree.js(265,36): error TS2304: Cannot find name 'Doc'. -src/language-js/printer-estree.js(266,62): error TS2304: Cannot find name 'Doc'. -src/language-js/printer-estree.js(273,12): error TS2304: Cannot find name 'FastPath'. -src/language-js/printer-estree.js(274,12): error TS2304: Cannot find name 'Options'. -src/language-js/printer-estree.js(400,9): error TS2769: No overload matches this call. +src/language-js/printer-estree.js(263,36): error TS2304: Cannot find name 'Doc'. +src/language-js/printer-estree.js(264,62): error TS2304: Cannot find name 'Doc'. +src/language-js/printer-estree.js(271,12): error TS2304: Cannot find name 'FastPath'. +src/language-js/printer-estree.js(272,12): error TS2304: Cannot find name 'Options'. +src/language-js/printer-estree.js(398,9): error TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): never[]', gave the following error. Argument of type '{ type: string; parts: any; } | { type: string; contents: any; n: any; }' is not assignable to parameter of type 'ConcatArray'. Type '{ type: string; parts: any; }' is missing the following properties from type 'ConcatArray': length, join, slice Overload 2 of 2, '(...items: ConcatArray[]): never[]', gave the following error. Argument of type '{ type: string; parts: any; } | { type: string; contents: any; n: any; }' is not assignable to parameter of type 'ConcatArray'. Type '{ type: string; parts: any; }' is not assignable to type 'ConcatArray'. -src/language-js/printer-estree.js(1481,28): error TS2769: No overload matches this call. - Overload 1 of 2, '(...items: ConcatArray[]): (string | { type: string; id: any; contents: any; break: boolean; expandedStates: any; })[]', gave the following error. - Argument of type '{ type: string; parts: any; }' is not assignable to parameter of type 'ConcatArray'. - Type '{ type: string; parts: any; }' is missing the following properties from type 'ConcatArray': length, join, slice - Overload 2 of 2, '(...items: (string | { type: string; id: any; contents: any; break: boolean; expandedStates: any; } | ConcatArray)[]): (string | { ...; })[]', gave the following error. - Argument of type '{ type: string; parts: any; }' is not assignable to parameter of type 'string | { type: string; id: any; contents: any; break: boolean; expandedStates: any; } | ConcatArray'. - Type '{ type: string; parts: any; }' is missing the following properties from type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }': id, contents, break, expandedStates -src/language-js/printer-estree.js(1914,20): error TS2345: Argument of type '" "' is not assignable to parameter of type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }'. -src/language-js/printer-estree.js(1916,20): error TS2345: Argument of type '{ type: string; parts: any; }' is not assignable to parameter of type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }'. -src/language-js/printer-estree.js(1918,18): error TS2345: Argument of type '"while ("' is not assignable to parameter of type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }'. -src/language-js/printer-estree.js(1927,9): error TS2345: Argument of type '")"' is not assignable to parameter of type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }'. -src/language-js/printer-estree.js(3473,11): error TS2769: No overload matches this call. +src/language-js/printer-estree.js(1897,20): error TS2345: Argument of type '" "' is not assignable to parameter of type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }'. +src/language-js/printer-estree.js(1899,20): error TS2345: Argument of type '{ type: string; parts: any; }' is not assignable to parameter of type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }'. + Type '{ type: string; parts: any; }' is missing the following properties from type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }': id, contents, break, expandedStates +src/language-js/printer-estree.js(1901,18): error TS2345: Argument of type '"while ("' is not assignable to parameter of type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }'. +src/language-js/printer-estree.js(1910,9): error TS2345: Argument of type '")"' is not assignable to parameter of type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }'. +src/language-js/printer-estree.js(3430,11): error TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray[]): never[]', gave the following error. Argument of type 'never[] | { type: string; parts: any; }' is not assignable to parameter of type 'ConcatArray'. Type '{ type: string; parts: any; }' is not assignable to type 'ConcatArray'. Overload 2 of 2, '(...items: ConcatArray[]): never[]', gave the following error. Argument of type 'never[] | { type: string; parts: any; }' is not assignable to parameter of type 'ConcatArray'. Type '{ type: string; parts: any; }' is not assignable to type 'ConcatArray'. -src/language-js/printer-estree.js(3902,22): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. -src/language-js/printer-estree.js(3969,14): error TS2339: Property 'comments' does not exist on type 'Expression'. - Property 'comments' does not exist on type 'Identifier'. -src/language-js/printer-estree.js(3981,9): error TS2367: This condition will always return 'false' since the types '"FunctionExpression" | "ClassExpression" | "ObjectExpression" | "TaggedTemplateExpression" | "CallExpression" | "ConditionalExpression" | "UpdateExpression" | "SequenceExpression" | ... 11 more ... | "MetaProperty"' and '"OptionalMemberExpression"' have no overlap. -src/language-js/printer-estree.js(3982,13): error TS2339: Property 'property' does not exist on type 'SimpleLiteral | RegExpLiteral | FunctionExpression | ArrowFunctionExpression | ArrayExpression | ... 16 more ... | AwaitExpression'. - Property 'property' does not exist on type 'SimpleLiteral'. -src/language-js/printer-estree.js(3982,52): error TS2339: Property 'property' does not exist on type 'SimpleLiteral | RegExpLiteral | FunctionExpression | ArrowFunctionExpression | ArrayExpression | ... 16 more ... | AwaitExpression'. - Property 'property' does not exist on type 'SimpleLiteral'. -src/language-js/printer-estree.js(3987,9): error TS2367: This condition will always return 'false' since the types '"FunctionExpression" | "ClassExpression" | "ObjectExpression" | "TaggedTemplateExpression" | "CallExpression" | "ConditionalExpression" | "UpdateExpression" | "SequenceExpression" | ... 11 more ... | "MetaProperty"' and '"OptionalMemberExpression"' have no overlap. -src/language-js/printer-estree.js(3989,29): error TS2339: Property 'object' does not exist on type 'SimpleLiteral | RegExpLiteral | FunctionExpression | ArrowFunctionExpression | ArrayExpression | ... 16 more ... | AwaitExpression'. - Property 'object' does not exist on type 'SimpleLiteral'. -src/language-js/printer-estree.js(3990,22): error TS2339: Property 'comments' does not exist on type 'SimpleLiteral | RegExpLiteral | FunctionExpression | ArrowFunctionExpression | ArrayExpression | ... 16 more ... | AwaitExpression'. - Property 'comments' does not exist on type 'SimpleLiteral'. -src/language-js/printer-estree.js(3996,9): error TS2367: This condition will always return 'false' since the types '"FunctionExpression" | "ClassExpression" | "ObjectExpression" | "TaggedTemplateExpression" | "CallExpression" | "ConditionalExpression" | "UpdateExpression" | "SequenceExpression" | ... 11 more ... | "MetaProperty"' and '"Identifier"' have no overlap. -src/language-js/printer-estree.js(3997,9): error TS2367: This condition will always return 'false' since the types '"FunctionExpression" | "ClassExpression" | "ObjectExpression" | "TaggedTemplateExpression" | "CallExpression" | "ConditionalExpression" | "UpdateExpression" | "SequenceExpression" | ... 11 more ... | "MetaProperty"' and '"ThisExpression"' have no overlap. -src/language-js/printer-estree.js(4201,23): error TS2532: Object is possibly 'undefined'. -src/language-js/printer-estree.js(4202,24): error TS2532: Object is possibly 'undefined'. -src/language-js/printer-estree.js(4558,5): error TS2345: Argument of type '"" | { type: string; parts: any; } | { type: string; contents: any; }' is not assignable to parameter of type 'string'. +src/language-js/printer-estree.js(3782,22): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. +src/language-js/printer-estree.js(3990,23): error TS2532: Object is possibly 'undefined'. +src/language-js/printer-estree.js(3991,24): error TS2532: Object is possibly 'undefined'. +src/language-js/printer-estree.js(4312,5): error TS2345: Argument of type '"" | { type: string; parts: any; } | { type: string; contents: any; }' is not assignable to parameter of type 'string'. Type '{ type: string; parts: any; }' is not assignable to type 'string'. -src/language-js/printer-estree.js(4562,16): error TS2345: Argument of type '{ type: string; parts: any; }' is not assignable to parameter of type 'string'. -src/language-js/printer-estree.js(4610,11): error TS2322: Type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }' is not assignable to type 'string'. -src/language-js/printer-estree.js(4625,11): error TS2322: Type '{ type: string; parts: any; }' is not assignable to type 'string'. -src/language-js/printer-estree.js(4637,9): error TS2345: Argument of type '{ type: string; parts: any; }' is not assignable to parameter of type 'string'. -src/language-js/printer-estree.js(4931,9): error TS2554: Expected 0-2 arguments, but got 3. -src/language-js/printer-estree.js(6138,7): error TS2769: No overload matches this call. +src/language-js/printer-estree.js(4316,16): error TS2345: Argument of type '{ type: string; parts: any; }' is not assignable to parameter of type 'string'. +src/language-js/printer-estree.js(4364,11): error TS2322: Type '{ type: string; id: any; contents: any; break: boolean; expandedStates: any; }' is not assignable to type 'string'. +src/language-js/printer-estree.js(4379,11): error TS2322: Type '{ type: string; parts: any; }' is not assignable to type 'string'. +src/language-js/printer-estree.js(4391,9): error TS2345: Argument of type '{ type: string; parts: any; }' is not assignable to parameter of type 'string'. +src/language-js/printer-estree.js(4664,9): error TS2554: Expected 0-2 arguments, but got 3. +src/language-js/printer-estree.js(5674,7): error TS2769: No overload matches this call. Overload 1 of 2, '(...items: ConcatArray<(childPath: any) => any>[]): ((childPath: any) => any)[]', gave the following error. Argument of type '(string | number)[]' is not assignable to parameter of type 'ConcatArray<(childPath: any) => any>'. The types returned by 'slice(...)' are incompatible between these types. @@ -269,7 +250,21 @@ src/language-js/printer-estree.js(6138,7): error TS2769: No overload matches thi Overload 2 of 2, '(...items: (((childPath: any) => any) | ConcatArray<(childPath: any) => any>)[]): ((childPath: any) => any)[]', gave the following error. Argument of type '(string | number)[]' is not assignable to parameter of type '((childPath: any) => any) | ConcatArray<(childPath: any) => any>'. Type '(string | number)[]' is not assignable to type 'ConcatArray<(childPath: any) => any>'. -src/language-js/utils.js(107,55): error TS2554: Expected 0-1 arguments, but got 2. +src/language-js/utils.js(118,55): error TS2554: Expected 0-1 arguments, but got 2. +src/language-js/utils.js(417,14): error TS2339: Property 'comments' does not exist on type 'Expression'. + Property 'comments' does not exist on type 'Identifier'. +src/language-js/utils.js(429,9): error TS2367: This condition will always return 'false' since the types '"FunctionExpression" | "ClassExpression" | "ObjectExpression" | "TaggedTemplateExpression" | "CallExpression" | "ConditionalExpression" | "UpdateExpression" | "SequenceExpression" | ... 11 more ... | "AwaitExpression"' and '"OptionalMemberExpression"' have no overlap. +src/language-js/utils.js(430,13): error TS2339: Property 'property' does not exist on type 'SimpleLiteral | RegExpLiteral | FunctionExpression | ArrowFunctionExpression | ArrayExpression | ... 16 more ... | AwaitExpression'. + Property 'property' does not exist on type 'SimpleLiteral'. +src/language-js/utils.js(430,52): error TS2339: Property 'property' does not exist on type 'SimpleLiteral | RegExpLiteral | FunctionExpression | ArrowFunctionExpression | ArrayExpression | ... 16 more ... | AwaitExpression'. + Property 'property' does not exist on type 'SimpleLiteral'. +src/language-js/utils.js(435,9): error TS2367: This condition will always return 'false' since the types '"FunctionExpression" | "ClassExpression" | "ObjectExpression" | "TaggedTemplateExpression" | "CallExpression" | "ConditionalExpression" | "UpdateExpression" | "SequenceExpression" | ... 11 more ... | "AwaitExpression"' and '"OptionalMemberExpression"' have no overlap. +src/language-js/utils.js(437,29): error TS2339: Property 'object' does not exist on type 'SimpleLiteral | RegExpLiteral | FunctionExpression | ArrowFunctionExpression | ArrayExpression | ... 16 more ... | AwaitExpression'. + Property 'object' does not exist on type 'SimpleLiteral'. +src/language-js/utils.js(438,22): error TS2339: Property 'comments' does not exist on type 'SimpleLiteral | RegExpLiteral | FunctionExpression | ArrowFunctionExpression | ArrayExpression | ... 16 more ... | AwaitExpression'. + Property 'comments' does not exist on type 'SimpleLiteral'. +src/language-js/utils.js(444,9): error TS2367: This condition will always return 'false' since the types '"FunctionExpression" | "ClassExpression" | "ObjectExpression" | "TaggedTemplateExpression" | "CallExpression" | "ConditionalExpression" | "UpdateExpression" | "SequenceExpression" | ... 11 more ... | "AwaitExpression"' and '"Identifier"' have no overlap. +src/language-js/utils.js(445,9): error TS2367: This condition will always return 'false' since the types '"FunctionExpression" | "ClassExpression" | "ObjectExpression" | "TaggedTemplateExpression" | "CallExpression" | "ConditionalExpression" | "UpdateExpression" | "SequenceExpression" | ... 11 more ... | "AwaitExpression"' and '"ThisExpression"' have no overlap. src/language-markdown/index.js(8,26): error TS2307: Cannot find module 'linguist-languages/data/Markdown'. src/language-markdown/index.js(21,26): error TS2307: Cannot find module 'linguist-languages/data/Markdown'. src/language-markdown/index.js(21,63): error TS2345: Argument of type '{ override: { name: string; since: string; parsers: string[]; vscodeLanguageIds: string[]; filenames: never[]; extensions: string[]; }; }' is not assignable to parameter of type '{ extend: any; override: any; exclude: any; }'. @@ -327,8 +322,8 @@ src/main/core.js(303,47): error TS2538: Type 'false' cannot be used as an index src/main/core.js(308,28): error TS2538: Type 'false' cannot be used as an index type. src/main/core.js(308,72): error TS2538: Type 'false' cannot be used as an index type. src/main/core.js(316,14): error TS2538: Type 'false' cannot be used as an index type. -src/main/options-normalizer.js(35,35): error TS2339: Property 'yellow' does not exist on type 'typeof import("../../../node_modules/chalk/types/index")'. -src/main/options-normalizer.js(36,35): error TS2339: Property 'blue' does not exist on type 'typeof import("../../../node_modules/chalk/types/index")'. +src/main/options-normalizer.js(35,35): error TS2339: Property 'yellow' does not exist on type 'typeof import("/prettier/prettier/node_modules/chalk/types/index")'. +src/main/options-normalizer.js(36,35): error TS2339: Property 'blue' does not exist on type 'typeof import("/prettier/prettier/node_modules/chalk/types/index")'. src/main/options-normalizer.js(54,5): error TS2525: Initializer provides no value for this binding element and the binding element has no default value. src/main/options-normalizer.js(74,16): error TS2341: Property '_hasDeprecationWarned' is private and only accessible within class 'Normalizer'. src/main/options-normalizer.js(80,39): error TS2341: Property '_hasDeprecationWarned' is private and only accessible within class 'Normalizer'. diff --git a/tests/baselines/reference/user/uglify-js.log b/tests/baselines/reference/user/uglify-js.log index 9fc9fb1cb67..79999aa8abd 100644 --- a/tests/baselines/reference/user/uglify-js.log +++ b/tests/baselines/reference/user/uglify-js.log @@ -1,12 +1,14 @@ Exit Code: 1 Standard output: node_modules/uglify-js/lib/ast.js(223,38): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/ast.js(906,5): error TS2322: Type '{ _visit: (node: any, descend: any) => any; parent: (n: any) => any; push: typeof push; pop: typeof pop; self: () => any; find_parent: (type: any) => any; has_directive: (type: any) => any; loopcontrol_target: (node: any) => any; in_boolean_context: () => boolean | undefined; }' is not assignable to type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(905,5): error TS2322: Type '{ _visit: (node: any, descend: any) => any; parent: (n: any) => any; push: typeof push; pop: typeof pop; self: () => any; find_parent: (type: any) => any; has_directive: (type: any) => any; loopcontrol_target: (node: any) => any; in_boolean_context: () => boolean | undefined; }' is not assignable to type 'TreeWalker'. Object literal may only specify known properties, but '_visit' does not exist in type 'TreeWalker'. Did you mean to write 'visit'? -node_modules/uglify-js/lib/ast.js(907,14): error TS2339: Property 'push' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/ast.js(914,14): error TS2339: Property 'pop' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/ast.js(969,25): error TS2339: Property 'self' does not exist on type 'TreeWalker'. -node_modules/uglify-js/lib/ast.js(970,37): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(906,14): error TS2339: Property 'push' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(913,14): error TS2339: Property 'pop' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(968,25): error TS2339: Property 'self' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(969,37): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(985,31): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. +node_modules/uglify-js/lib/ast.js(989,29): error TS2339: Property 'parent' does not exist on type 'TreeWalker'. node_modules/uglify-js/lib/compress.js(184,42): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(535,41): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/compress.js(861,33): error TS2554: Expected 0 arguments, but got 1. @@ -19,58 +21,57 @@ node_modules/uglify-js/lib/compress.js(1240,112): error TS2454: Variable 'args' node_modules/uglify-js/lib/compress.js(1241,29): error TS2532: Object is possibly 'undefined'. node_modules/uglify-js/lib/compress.js(1250,87): error TS2322: Type 'false' is not assignable to type 'number'. node_modules/uglify-js/lib/compress.js(1258,29): error TS2322: Type 'false' is not assignable to type 'never'. -node_modules/uglify-js/lib/compress.js(1366,53): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1467,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(1577,42): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1609,41): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(1721,49): error TS2345: Argument of type 'number[]' is not assignable to parameter of type '[number, number, ...never[]]'. +node_modules/uglify-js/lib/compress.js(1367,53): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1468,38): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(1578,42): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1610,41): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(1722,49): error TS2345: Argument of type 'number[]' is not assignable to parameter of type '[number, number, ...never[]]'. Type 'number[]' is missing the following properties from type '[number, number, ...never[]]': 0, 1 -node_modules/uglify-js/lib/compress.js(2044,59): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(2082,53): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[number, number, ...never[]]'. +node_modules/uglify-js/lib/compress.js(2045,59): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(2083,53): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[number, number, ...never[]]'. Type 'any[]' is missing the following properties from type '[number, number, ...never[]]': 0, 1 -node_modules/uglify-js/lib/compress.js(2230,34): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(2949,42): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3402,38): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3415,33): error TS2322: Type '"f"' is not assignable to type 'boolean'. -node_modules/uglify-js/lib/compress.js(3549,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3602,29): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3619,29): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(3644,75): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3718,63): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3839,12): error TS2339: Property 'push' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(3914,38): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(3935,24): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(3945,28): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. -node_modules/uglify-js/lib/compress.js(4114,21): error TS2403: Subsequent variable declarations must have the same type. Variable 'defs' must be of type 'Dictionary', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(4166,17): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. -node_modules/uglify-js/lib/compress.js(4229,45): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4340,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4638,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(4722,37): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(4930,57): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[string | RegExp, (string | undefined)?]'. +node_modules/uglify-js/lib/compress.js(2231,34): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(2950,42): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3404,38): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3428,33): error TS2322: Type '"f"' is not assignable to type 'boolean'. +node_modules/uglify-js/lib/compress.js(3562,33): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3615,29): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3632,29): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(3657,75): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3731,63): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3852,12): error TS2339: Property 'push' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(3927,38): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(3948,24): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(3958,28): error TS2339: Property 'parent' does not exist on type 'TreeTransformer'. +node_modules/uglify-js/lib/compress.js(4183,17): error TS2447: The '|=' operator is not allowed for boolean types. Consider using '||' instead. +node_modules/uglify-js/lib/compress.js(4246,45): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4357,33): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4655,17): error TS2403: Subsequent variable declarations must have the same type. Variable 'body' must be of type 'any[]', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(4739,37): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(4947,57): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[string | RegExp, (string | undefined)?]'. Property '0' is missing in type 'any[]' but required in type '[string | RegExp, (string | undefined)?]'. -node_modules/uglify-js/lib/compress.js(5094,45): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(5101,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'code' must be of type 'string', but here has type '{ get: () => string; toString: () => string; indent: () => void; indentation: () => number; current_width: () => number; should_break: () => boolean; has_parens: () => boolean; newline: () => void; print: (str: any) => void; ... 24 more ...; parent: (n: any) => any; }'. -node_modules/uglify-js/lib/compress.js(5105,36): error TS2532: Object is possibly 'undefined'. -node_modules/uglify-js/lib/compress.js(5110,41): error TS2339: Property 'get' does not exist on type 'string'. -node_modules/uglify-js/lib/compress.js(5623,18): error TS2454: Variable 'is_strict_comparison' is used before being assigned. -node_modules/uglify-js/lib/compress.js(6134,25): error TS2367: This condition will always return 'false' since the types 'boolean' and 'string' have no overlap. -node_modules/uglify-js/lib/compress.js(6161,47): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(6234,39): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(6306,39): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(6312,41): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/compress.js(6757,43): error TS2454: Variable 'property' is used before being assigned. -node_modules/uglify-js/lib/compress.js(6772,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(6775,46): error TS2339: Property 'has_side_effects' does not exist on type 'number'. -node_modules/uglify-js/lib/compress.js(6781,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. -node_modules/uglify-js/lib/compress.js(6819,34): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/minify.js(167,75): error TS2339: Property 'compress' does not exist on type 'Compressor'. +node_modules/uglify-js/lib/compress.js(5111,45): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(5118,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'code' must be of type 'string', but here has type '{ get: () => string; toString: () => string; indent: () => void; indentation: () => number; current_width: () => number; should_break: () => boolean; has_parens: () => boolean; newline: () => void; print: (str: any) => void; ... 23 more ...; parent: (n: any) => any; }'. +node_modules/uglify-js/lib/compress.js(5122,36): error TS2532: Object is possibly 'undefined'. +node_modules/uglify-js/lib/compress.js(5127,41): error TS2339: Property 'get' does not exist on type 'string'. +node_modules/uglify-js/lib/compress.js(5642,18): error TS2454: Variable 'is_strict_comparison' is used before being assigned. +node_modules/uglify-js/lib/compress.js(6149,25): error TS2367: This condition will always return 'false' since the types 'boolean' and 'string' have no overlap. +node_modules/uglify-js/lib/compress.js(6176,47): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6249,39): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6321,39): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6327,41): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/compress.js(6772,43): error TS2454: Variable 'property' is used before being assigned. +node_modules/uglify-js/lib/compress.js(6787,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(6790,46): error TS2339: Property 'has_side_effects' does not exist on type 'number'. +node_modules/uglify-js/lib/compress.js(6796,25): error TS2403: Subsequent variable declarations must have the same type. Variable 'value' must be of type 'number', but here has type 'any'. +node_modules/uglify-js/lib/compress.js(6834,34): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/minify.js(186,75): error TS2339: Property 'compress' does not exist on type 'Compressor'. node_modules/uglify-js/lib/mozilla-ast.js(566,33): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/output.js(235,25): error TS2554: Expected 0 arguments, but got 2. -node_modules/uglify-js/lib/output.js(459,37): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/output.js(764,38): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/output.js(1160,44): error TS2554: Expected 0 arguments, but got 1. -node_modules/uglify-js/lib/output.js(1442,58): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. +node_modules/uglify-js/lib/output.js(234,25): error TS2554: Expected 0 arguments, but got 2. +node_modules/uglify-js/lib/output.js(458,37): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/output.js(762,38): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/output.js(1158,44): error TS2554: Expected 0 arguments, but got 1. +node_modules/uglify-js/lib/output.js(1459,58): error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type. node_modules/uglify-js/lib/parse.js(361,20): error TS2345: Argument of type 'number | undefined' is not assignable to parameter of type 'number'. Type 'undefined' is not assignable to type 'number'. node_modules/uglify-js/lib/parse.js(443,32): error TS2345: Argument of type 'any' is not assignable to parameter of type 'never'. @@ -115,8 +116,6 @@ node_modules/uglify-js/lib/scope.js(460,30): error TS2554: Expected 0 arguments, node_modules/uglify-js/lib/scope.js(485,30): error TS2554: Expected 0 arguments, but got 1. node_modules/uglify-js/lib/sourcemap.js(55,25): error TS2304: Cannot find name 'MOZ_SourceMap'. node_modules/uglify-js/lib/sourcemap.js(61,23): error TS2304: Cannot find name 'MOZ_SourceMap'. -node_modules/uglify-js/tools/exit.js(7,32): error TS2339: Property 'bufferSize' does not exist on type 'WriteStream'. -node_modules/uglify-js/tools/exit.js(7,61): error TS2339: Property 'bufferSize' does not exist on type 'WriteStream'. node_modules/uglify-js/tools/exit.js(10,37): error TS2345: Argument of type 'any[]' is not assignable to parameter of type '[(number | undefined)?]'. Types of property 'length' are incompatible. Type 'number' is not assignable to type '0 | 1'. diff --git a/tests/baselines/reference/user/webpack.log b/tests/baselines/reference/user/webpack.log new file mode 100644 index 00000000000..a660ffbad3f --- /dev/null +++ b/tests/baselines/reference/user/webpack.log @@ -0,0 +1,34 @@ +Exit Code: 1 +Standard output: +lib/BannerPlugin.js(34,27): error TS2345: Argument of type 'BannerPluginArgument' is not assignable to parameter of type 'object | object[]'. + Type 'string' is not assignable to type 'object | object[]'. +lib/logging/Logger.js(49,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(53,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(57,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(61,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(65,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(70,21): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(75,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(79,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(83,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(87,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(91,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(95,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(99,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(103,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(117,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/logging/Logger.js(127,20): error TS2345: Argument of type 'string' is not assignable to parameter of type '"error" | "time" | "group" | "debug" | "log" | "info" | "warn" | "trace" | "groupCollapsed" | "groupEnd" | "profile" | "profileEnd" | "clear" | "status"'. +lib/util/registerExternalSerializer.js(253,14): error TS2339: Property 'line' does not exist on type 'Position'. +lib/util/registerExternalSerializer.js(254,14): error TS2339: Property 'column' does not exist on type 'Position'. +lib/validateSchema.js(15,11): error TS2339: Property 'children' does not exist on type 'ErrorObject'. +lib/validateSchema.js(16,11): error TS2339: Property 'children' does not exist on type 'ErrorObject'. +lib/validateSchema.js(26,22): error TS2339: Property 'additionalProperty' does not exist on type 'ErrorParameters'. + Property 'additionalProperty' does not exist on type 'RefParams'. +lib/validateSchema.js(40,22): error TS2339: Property 'additionalProperty' does not exist on type 'ErrorParameters'. + Property 'additionalProperty' does not exist on type 'RefParams'. +lib/validateSchema.js(51,31): error TS2339: Property 'additionalProperty' does not exist on type 'ErrorParameters'. + Property 'additionalProperty' does not exist on type 'RefParams'. + + + +Standard error: diff --git a/tests/cases/compiler/javascriptDefinePropertyPrototypeNonConstructor.ts b/tests/cases/compiler/javascriptDefinePropertyPrototypeNonConstructor.ts new file mode 100644 index 00000000000..830ca4376b3 --- /dev/null +++ b/tests/cases/compiler/javascriptDefinePropertyPrototypeNonConstructor.ts @@ -0,0 +1,14 @@ +// @allowJs: true +// @checkJs: false +// @noEmit: true +// @Filename: /a.js + +function Graphic() { +} + +Object.defineProperty(Graphic.prototype, "instance", { + get: function() { + return this; + } +}); + diff --git a/tests/cases/compiler/javascriptImportDefaultBadExport.ts b/tests/cases/compiler/javascriptImportDefaultBadExport.ts new file mode 100644 index 00000000000..c1f2455e11d --- /dev/null +++ b/tests/cases/compiler/javascriptImportDefaultBadExport.ts @@ -0,0 +1,12 @@ +// https://github.com/microsoft/TypeScript/issues/34481 + +// @allowJs: true +// @checkJs: true +// @noEmit: true + +// @Filename: /a.js +const alias = {}; +module.exports = alias; + +// @Filename: /b.js +import a from "./a"; diff --git a/tests/cases/compiler/jsCheckObjectDefineThisNoCrash.ts b/tests/cases/compiler/jsCheckObjectDefineThisNoCrash.ts new file mode 100644 index 00000000000..15fbbb1433a --- /dev/null +++ b/tests/cases/compiler/jsCheckObjectDefineThisNoCrash.ts @@ -0,0 +1,11 @@ +// @checkJs: true +// @allowJs: true +// @noEmit: true +// @filename: jsCheckObjectDefineThisNoCrash.js +class C { + constructor() { + // Neither of the following should be recognized as declarations yet + Object.defineProperty(this, "_prop", { value: {} }); + Object.defineProperty(this._prop, "num", { value: 12 }); + } +} \ No newline at end of file diff --git a/tests/cases/compiler/jsxDeclarationsWithEsModuleInteropNoCrash.tsx b/tests/cases/compiler/jsxDeclarationsWithEsModuleInteropNoCrash.tsx new file mode 100644 index 00000000000..4c74c67fb3a --- /dev/null +++ b/tests/cases/compiler/jsxDeclarationsWithEsModuleInteropNoCrash.tsx @@ -0,0 +1,29 @@ +// @allowJs: true +// @checkJs: true +// @emitDeclarationOnly: true +// @declaration: true +// @strict: true +// @esModuleInterop: true +// @jsx: react +// @noImplicitAny: false +// @filename: jsxDeclarationsWithEsModuleInteropNoCrash.jsx +/// +import PropTypes from 'prop-types'; +import React from 'react'; + +const propTypes = { + bar: PropTypes.bool, +}; + +const defaultProps = { + bar: false, +}; + +function Foo({ bar }) { + return

{bar}
; +} + +Foo.propTypes = propTypes; +Foo.defaultProps = defaultProps; + +export default Foo; \ No newline at end of file diff --git a/tests/cases/compiler/noEmitAndComposite.ts b/tests/cases/compiler/noEmitAndComposite.ts deleted file mode 100644 index 849fdb04da1..00000000000 --- a/tests/cases/compiler/noEmitAndComposite.ts +++ /dev/null @@ -1,10 +0,0 @@ -// @Filename: /a.ts -const x = 10; - -// @Filename: /tsconfig.json -{ - "compilerOptions": { - "noEmit": true, - "composite": true - } -} diff --git a/tests/cases/compiler/noEmitAndIncremental.ts b/tests/cases/compiler/noEmitAndIncremental.ts deleted file mode 100644 index 0349496c1ef..00000000000 --- a/tests/cases/compiler/noEmitAndIncremental.ts +++ /dev/null @@ -1,11 +0,0 @@ -// @Filename: /a.ts -const x = 10; - -// @Filename: /tsconfig.json -{ - "compilerOptions": { - "noEmit": true, - "incremental": true - } -} - diff --git a/tests/cases/compiler/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.ts b/tests/cases/compiler/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.ts index dd3513f9b3a..0c6c1566df3 100644 --- a/tests/cases/compiler/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.ts +++ b/tests/cases/compiler/noImplicitAnyAndPrivateMembersWithoutTypeAnnotations.ts @@ -3,6 +3,8 @@ declare class Something { private static someStaticVar; private someVar; + private get getter(); + private set setter(v); } // @noimplicitany: true diff --git a/tests/cases/compiler/reachabilityChecks4.ts b/tests/cases/compiler/reachabilityChecks4.ts index f07395ac38e..a853a6e996a 100644 --- a/tests/cases/compiler/reachabilityChecks4.ts +++ b/tests/cases/compiler/reachabilityChecks4.ts @@ -12,4 +12,55 @@ function foo(x, y) { case 4: return 3; } -} \ No newline at end of file +} + +declare function noop(): void; +declare function fail(): never; + +function f1(x: 0 | 1 | 2) { + switch (x) { + case 0: + fail(); + case 1: + noop(); + case 2: + return; + } +} + +// Repro from #34021 + +type Behavior = 'SLIDE' | 'SLIDE_OUT' +type Direction = 'LEFT' | 'RIGHT' | 'TOP' | 'BOTTOM' + +interface Transition { + behavior: Behavior + direction: Direction +} + +function f2(transition: Transition): any { + switch (transition.behavior) { + case 'SLIDE': + switch (transition.direction) { + case 'LEFT': + return [] + case 'RIGHT': + return [] + case 'TOP': + return [] + case 'BOTTOM': + return [] + } + case 'SLIDE_OUT': + switch (transition.direction) { + case 'LEFT': + return [] + case 'RIGHT': + return [] + case 'TOP': + return [] + case 'BOTTOM': + return [] + } + } +} diff --git a/tests/cases/compiler/reservedWords2.ts b/tests/cases/compiler/reservedWords2.ts index 54482264d0e..fe261f0cf4d 100644 --- a/tests/cases/compiler/reservedWords2.ts +++ b/tests/cases/compiler/reservedWords2.ts @@ -8,5 +8,6 @@ var {while, return} = { while: 1, return: 2 }; var {this, switch: { continue} } = { this: 1, switch: { continue: 2 }}; var [debugger, if] = [1, 2]; enum void {} - +function f(default: number) {} +class C { m(null: string) {} } diff --git a/tests/cases/conformance/classes/propertyMemberDeclarations/instanceMemberWithComputedPropertyName2.ts b/tests/cases/conformance/classes/propertyMemberDeclarations/instanceMemberWithComputedPropertyName2.ts new file mode 100644 index 00000000000..e597b6b9d97 --- /dev/null +++ b/tests/cases/conformance/classes/propertyMemberDeclarations/instanceMemberWithComputedPropertyName2.ts @@ -0,0 +1,8 @@ +// https://github.com/microsoft/TypeScript/issues/33857 +// @useDefineForClassFields: true +// @target: es2015 +"use strict"; +const x = 1; +class C { + [x]: string; +} diff --git a/tests/cases/conformance/controlFlow/assertionTypePredicates1.ts b/tests/cases/conformance/controlFlow/assertionTypePredicates1.ts index 4cc73d5c917..1b7db7affaa 100644 --- a/tests/cases/conformance/controlFlow/assertionTypePredicates1.ts +++ b/tests/cases/conformance/controlFlow/assertionTypePredicates1.ts @@ -1,4 +1,5 @@ // @strict: true +// @allowUnreachableCode: false // @declaration: true declare function isString(value: unknown): value is string; @@ -37,6 +38,14 @@ function f01(x: unknown) { assertDefined(x); x; // string } + if (!!true) { + assert(false); + x; // Unreachable + } + if (!!true) { + assert(false && x === undefined); + x; // Unreachable + } } function f02(x: string | undefined) { @@ -77,6 +86,10 @@ function f10(x: string | undefined) { Debug.assertDefined(x); x.length; } + if (!!true) { + Debug.assert(false); + x; // Unreachable + } } class Test { @@ -108,6 +121,10 @@ class Test { this.assertIsTest2(); this.z; } + baz(x: number) { + this.assert(false); + x; // Unreachable + } } class Test2 extends Test { diff --git a/tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts b/tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts index dadb1b36076..49ebd3807db 100644 --- a/tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts +++ b/tests/cases/conformance/controlFlow/controlFlowOptionalChain.ts @@ -61,8 +61,8 @@ o2.f; declare const o3: { x: 1, y: string } | { x: 2, y: number } | undefined; if (o3?.x === 1) { - o3; // TODO: should be `{ x: y, y: string }` - o3.x; // TODO: should not be an error. + o3; + o3.x; o3?.x; } else { @@ -161,3 +161,370 @@ function f01(x: unknown) { x; } } + +type Thing = { foo: string | number, bar(): number, baz: object }; + +function f10(o: Thing | undefined, value: number) { + if (o?.foo === value) { + o.foo; + } + if (o?.["foo"] === value) { + o["foo"]; + } + if (o?.bar() === value) { + o.bar; + } + if (o?.foo == value) { + o.foo; + } + if (o?.["foo"] == value) { + o["foo"]; + } + if (o?.bar() == value) { + o.bar; + } +} + +function f11(o: Thing | null, value: number) { + if (o?.foo === value) { + o.foo; + } + if (o?.["foo"] === value) { + o["foo"]; + } + if (o?.bar() === value) { + o.bar; + } + if (o?.foo == value) { + o.foo; + } + if (o?.["foo"] == value) { + o["foo"]; + } + if (o?.bar() == value) { + o.bar; + } +} + +function f12(o: Thing | undefined, value: number | undefined) { + if (o?.foo === value) { + o.foo; // Error + } + if (o?.["foo"] === value) { + o["foo"]; // Error + } + if (o?.bar() === value) { + o.bar; // Error + } + if (o?.foo == value) { + o.foo; // Error + } + if (o?.["foo"] == value) { + o["foo"]; // Error + } + if (o?.bar() == value) { + o.bar; // Error + } +} + +function f12a(o: Thing | undefined, value: number | null) { + if (o?.foo === value) { + o.foo; + } + if (o?.["foo"] === value) { + o["foo"]; + } + if (o?.bar() === value) { + o.bar; + } + if (o?.foo == value) { + o.foo; // Error + } + if (o?.["foo"] == value) { + o["foo"]; // Error + } + if (o?.bar() == value) { + o.bar; // Error + } +} + +function f13(o: Thing | undefined) { + if (o?.foo !== undefined) { + o.foo; + } + if (o?.["foo"] !== undefined) { + o["foo"]; + } + if (o?.bar() !== undefined) { + o.bar; + } + if (o?.foo != undefined) { + o.foo; + } + if (o?.["foo"] != undefined) { + o["foo"]; + } + if (o?.bar() != undefined) { + o.bar; + } +} + +function f13a(o: Thing | undefined) { + if (o?.foo !== null) { + o.foo; // Error + } + if (o?.["foo"] !== null) { + o["foo"]; // Error + } + if (o?.bar() !== null) { + o.bar; // Error + } + if (o?.foo != null) { + o.foo; + } + if (o?.["foo"] != null) { + o["foo"]; + } + if (o?.bar() != null) { + o.bar; + } +} + +function f14(o: Thing | null) { + if (o?.foo !== undefined) { + o.foo; + } + if (o?.["foo"] !== undefined) { + o["foo"]; + } + if (o?.bar() !== undefined) { + o.bar; + } +} + +function f15(o: Thing | undefined, value: number) { + if (o?.foo === value) { + o.foo; + } + else { + o.foo; // Error + } + if (o?.foo !== value) { + o.foo; // Error + } + else { + o.foo; + } + if (o?.foo == value) { + o.foo; + } + else { + o.foo; // Error + } + if (o?.foo != value) { + o.foo; // Error + } + else { + o.foo; + } +} + +function f16(o: Thing | undefined) { + if (o?.foo === undefined) { + o.foo; // Error + } + else { + o.foo; + } + if (o?.foo !== undefined) { + o.foo; + } + else { + o.foo; // Error + } + if (o?.foo == undefined) { + o.foo; // Error + } + else { + o.foo; + } + if (o?.foo != undefined) { + o.foo; + } + else { + o.foo; // Error + } +} + +function f20(o: Thing | undefined) { + if (typeof o?.foo === "number") { + o.foo; + } + if (typeof o?.["foo"] === "number") { + o["foo"]; + } + if (typeof o?.bar() === "number") { + o.bar; + } + if (o?.baz instanceof Error) { + o.baz; + } +} + +function f21(o: Thing | null) { + if (typeof o?.foo === "number") { + o.foo; + } + if (typeof o?.["foo"] === "number") { + o["foo"]; + } + if (typeof o?.bar() === "number") { + o.bar; + } + if (o?.baz instanceof Error) { + o.baz; + } +} + +function f22(o: Thing | undefined) { + if (typeof o?.foo === "number") { + o.foo; + } + else { + o.foo; // Error + } + if (typeof o?.foo !== "number") { + o.foo; // Error + } + else { + o.foo; + } + if (typeof o?.foo == "number") { + o.foo; + } + else { + o.foo; // Error + } + if (typeof o?.foo != "number") { + o.foo; // Error + } + else { + o.foo; + } +} + +function f23(o: Thing | undefined) { + if (typeof o?.foo === "undefined") { + o.foo; // Error + } + else { + o.foo; + } + if (typeof o?.foo !== "undefined") { + o.foo; + } + else { + o.foo; // Error + } + if (typeof o?.foo == "undefined") { + o.foo; // Error + } + else { + o.foo; + } + if (typeof o?.foo != "undefined") { + o.foo; + } + else { + o.foo; // Error + } +} + +declare function assert(x: unknown): asserts x; +declare function assertNonNull(x: T): asserts x is NonNullable; + +function f30(o: Thing | undefined) { + if (!!true) { + assert(o?.foo); + o.foo; + } + if (!!true) { + assert(o?.foo === 42); + o.foo; + } + if (!!true) { + assert(typeof o?.foo === "number"); + o.foo; + } + if (!!true) { + assertNonNull(o?.foo); + o.foo; + } +} + +function f40(o: Thing | undefined) { + switch (o?.foo) { + case "abc": + o.foo; + break; + case 42: + o.foo; + break; + case undefined: + o.foo; // Error + break; + default: + o.foo; // Error + break; + } +} + +function f41(o: Thing | undefined) { + switch (typeof o?.foo) { + case "string": + o.foo; + break; + case "number": + o.foo; + break; + case "undefined": + o.foo; // Error + break; + default: + o.foo; // Error + break; + } +} + +// Repros from #34570 + +type Shape = + | { type: 'rectangle', width: number, height: number } + | { type: 'circle', radius: number } + +function getArea(shape?: Shape) { + switch (shape?.type) { + case 'circle': + return Math.PI * shape.radius ** 2 + case 'rectangle': + return shape.width * shape.height + default: + return 0 + } +} + +type Feature = { + id: string; + geometry?: { + type: string; + coordinates: number[]; + }; +}; + + +function extractCoordinates(f: Feature): number[] { + if (f.geometry?.type !== 'test') { + return []; + } + return f.geometry.coordinates; +} diff --git a/tests/cases/conformance/es2019/globalThisGlobalExportAsGlobal.ts b/tests/cases/conformance/es2019/globalThisGlobalExportAsGlobal.ts new file mode 100644 index 00000000000..b5f6c8927bf --- /dev/null +++ b/tests/cases/conformance/es2019/globalThisGlobalExportAsGlobal.ts @@ -0,0 +1,4 @@ +// https://github.com/microsoft/TypeScript/issues/33754 +declare global { + export { globalThis as global } +} diff --git a/tests/cases/conformance/expressions/nullishCoalescingOperator/nullishCoalescingOperator12.ts b/tests/cases/conformance/expressions/nullishCoalescingOperator/nullishCoalescingOperator12.ts new file mode 100644 index 00000000000..500340380b8 --- /dev/null +++ b/tests/cases/conformance/expressions/nullishCoalescingOperator/nullishCoalescingOperator12.ts @@ -0,0 +1,5 @@ +// @strict: true +// @target: ES2015 + +const obj: { arr: any[] } = { arr: [] }; +for (const i of obj?.arr ?? []) { } diff --git a/tests/cases/conformance/expressions/optionalChaining/callChain/callChain.ts b/tests/cases/conformance/expressions/optionalChaining/callChain/callChain.ts index fa24d920a19..bbfc3aa42f9 100644 --- a/tests/cases/conformance/expressions/optionalChaining/callChain/callChain.ts +++ b/tests/cases/conformance/expressions/optionalChaining/callChain/callChain.ts @@ -32,4 +32,8 @@ o3["b"]?.(1, ...[2, 3], 4).c; declare const o4: undefined | ((f: (a: T) => T) => T); declare function incr(x: number): number; -const v: number | undefined = o4?.(incr); \ No newline at end of file +const v: number | undefined = o4?.(incr); + +// GH#33744 +declare const o5: () => undefined | (() => void); +o5()?.(); \ No newline at end of file diff --git a/tests/cases/conformance/expressions/optionalChaining/elementAccessChain/elementAccessChain.ts b/tests/cases/conformance/expressions/optionalChaining/elementAccessChain/elementAccessChain.ts index 6718c050a03..20dfaab0c86 100644 --- a/tests/cases/conformance/expressions/optionalChaining/elementAccessChain/elementAccessChain.ts +++ b/tests/cases/conformance/expressions/optionalChaining/elementAccessChain/elementAccessChain.ts @@ -20,3 +20,7 @@ o5.b?.()["c"].d?.e; o5.b?.()["c"].d?.["e"]; o5["b"]?.()["c"].d?.e; o5["b"]?.()["c"].d?.["e"]; + +// GH#33744 +declare const o6: () => undefined | ({ x: number }); +o6()?.["x"]; \ No newline at end of file diff --git a/tests/cases/conformance/expressions/optionalChaining/propertyAccessChain/propertyAccessChain.ts b/tests/cases/conformance/expressions/optionalChaining/propertyAccessChain/propertyAccessChain.ts index e76d95b4540..1f9e0bc0550 100644 --- a/tests/cases/conformance/expressions/optionalChaining/propertyAccessChain/propertyAccessChain.ts +++ b/tests/cases/conformance/expressions/optionalChaining/propertyAccessChain/propertyAccessChain.ts @@ -14,3 +14,10 @@ o4.b?.c.d?.e; declare const o5: { b?(): { c: { d?: { e: string } } } }; o5.b?.().c.d?.e; + +// GH#33744 +declare const o6: () => undefined | ({ x: number }); +o6()?.x; + +// GH#34109 +o1?.b ? 1 : 0; \ No newline at end of file diff --git a/tests/cases/conformance/jsdoc/callOfPropertylessConstructorFunction.ts b/tests/cases/conformance/jsdoc/callOfPropertylessConstructorFunction.ts new file mode 100644 index 00000000000..213b66908d9 --- /dev/null +++ b/tests/cases/conformance/jsdoc/callOfPropertylessConstructorFunction.ts @@ -0,0 +1,11 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @Filename: callOfPropertylessConstructorFunction.js +/** + * @constructor + */ +function Dependency(j) { + return j +} +Dependency({}) diff --git a/tests/cases/conformance/jsdoc/jsdocTypeReferenceToValue.ts b/tests/cases/conformance/jsdoc/jsdocTypeReferenceToValue.ts new file mode 100644 index 00000000000..4f3ba385ac5 --- /dev/null +++ b/tests/cases/conformance/jsdoc/jsdocTypeReferenceToValue.ts @@ -0,0 +1,8 @@ +// @Filename: foo.js +// @noEmit: true +// @allowJs: true +// @checkJs: true +/** @param {Image} image */ +function process(image) { + return new image(1, 1) +} diff --git a/tests/cases/conformance/jsdoc/moduleExportsElementAccessAssignment2.ts b/tests/cases/conformance/jsdoc/moduleExportsElementAccessAssignment2.ts new file mode 100644 index 00000000000..5be5e803efb --- /dev/null +++ b/tests/cases/conformance/jsdoc/moduleExportsElementAccessAssignment2.ts @@ -0,0 +1,22 @@ +// @noEmit: true +// @checkJs: true +// @allowJs: true +// @strict: true +// @Filename: file1.js + +// this file _should_ be a global file +var GlobalThing = { x: 12 }; + +/** + * @param {*} type + * @param {*} ctor + * @param {*} exports + */ +function f(type, ctor, exports) { + if (typeof exports !== "undefined") { + exports["AST_" + type] = ctor; + } +} + +// @Filename: ref.js +GlobalThing.x diff --git a/tests/cases/conformance/salsa/circularMultipleAssignmentDeclaration.ts b/tests/cases/conformance/salsa/circularMultipleAssignmentDeclaration.ts new file mode 100644 index 00000000000..bc2c992dafc --- /dev/null +++ b/tests/cases/conformance/salsa/circularMultipleAssignmentDeclaration.ts @@ -0,0 +1,6 @@ +// @filename:circularMultipleAssignmentDeclaration.js +// @allowJs: true +// @checkJs: true +// @noEmit: true +ns.next = ns.next || { shared: {} }; +ns.next.shared.mymethod = {}; diff --git a/tests/cases/conformance/salsa/importAliasModuleExports.ts b/tests/cases/conformance/salsa/importAliasModuleExports.ts new file mode 100644 index 00000000000..5e850206676 --- /dev/null +++ b/tests/cases/conformance/salsa/importAliasModuleExports.ts @@ -0,0 +1,15 @@ +// @allowJs: true +// @checkJs: true +// @noEmit: true +// @esModuleInterop: true +// @filename: mod1.js +class Alias { + bar() { return 1 } +} +module.exports = Alias; + +// @filename: main.js +import A from './mod1' +A.prototype.foo = 0 +new A().bar +new A().foo diff --git a/tests/cases/conformance/types/thisType/thisTypeOptionalCall.ts b/tests/cases/conformance/types/thisType/thisTypeOptionalCall.ts new file mode 100644 index 00000000000..b3f35a596ea --- /dev/null +++ b/tests/cases/conformance/types/thisType/thisTypeOptionalCall.ts @@ -0,0 +1,8 @@ +// @strictNullChecks: true +// @noImplicitAny: true +// @noImplicitThis: true +// @strictBindCallApply: false + +function maybeBind(obj: T, fn: ((this: T, ...args: A) => R) | undefined): ((...args: A) => R) | undefined { + return fn?.bind(obj); +} \ No newline at end of file diff --git a/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts b/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts index d64b1973695..12a5e8b17cb 100644 --- a/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts +++ b/tests/cases/conformance/types/typeRelationships/typeInference/unionAndIntersectionInference3.ts @@ -54,3 +54,37 @@ let y1 = foo1(sx); // string let x2 = foo2(sa); // unknown let y2 = foo2(sx); // { extra: number } + +// Repro from #33490 + +declare class Component

{ props: P } + +export type ComponentClass

= new (props: P) => Component

; +export type FunctionComponent

= (props: P) => null; + +export type ComponentType

= FunctionComponent

| ComponentClass

; + +export interface RouteComponentProps { route: string } + +declare function withRouter< + P extends RouteComponentProps, + C extends ComponentType

+>( + component: C & ComponentType

+): ComponentClass>; + +interface Props extends RouteComponentProps { username: string } + +declare const MyComponent: ComponentType; + +withRouter(MyComponent); + +// Repro from #33490 + +type AB = { a: T } | { b: T }; + +// T & AB normalizes to T & { a: U } | T & { b: U } below +declare function foo(obj: T & AB): [T, U]; +declare let ab: AB; + +let z = foo(ab); // [AB, string] diff --git a/tests/cases/fourslash/codeFixInferFromUsageContextualImport1.ts b/tests/cases/fourslash/codeFixInferFromUsageContextualImport1.ts new file mode 100644 index 00000000000..5e4a4ca3542 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageContextualImport1.ts @@ -0,0 +1,28 @@ +/// + +// @strict: true +// @noImplicitAny: true +// @noLib: true + +// @Filename: /a.ts +////export interface User {} +////export declare function getEmail(user: User): string; + +// @Filename: /b.ts +////import { getEmail } from "./a"; +//// +////export function f([|user|]) { +//// getEmail(user); +////} + +goTo.file("/b.ts"); + +verify.codeFix({ + description: "Infer parameter types from usage", + newFileContent: +`import { getEmail, User } from "./a"; + +export function f(user: User) { + getEmail(user); +}` +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageContextualImport2.ts b/tests/cases/fourslash/codeFixInferFromUsageContextualImport2.ts new file mode 100644 index 00000000000..f12f9dc9e80 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageContextualImport2.ts @@ -0,0 +1,28 @@ +/// + +// @strict: true +// @noImplicitAny: true +// @noLib: true + +// @Filename: /types.d.ts +////declare function getEmail(user: import('./a').User): string; + +// @Filename: /a.ts +////export interface User {} + +// @Filename: /b.ts +////export function f([|user|]) { +//// getEmail(user); +////} + +goTo.file("/b.ts"); + +verify.codeFix({ + description: "Infer parameter types from usage", + newFileContent: +`import { User } from "./a"; + +export function f(user: User) { + getEmail(user); +}` +}); diff --git a/tests/cases/fourslash/codeFixInferFromUsageContextualImport3.ts b/tests/cases/fourslash/codeFixInferFromUsageContextualImport3.ts new file mode 100644 index 00000000000..1009e6d0a25 --- /dev/null +++ b/tests/cases/fourslash/codeFixInferFromUsageContextualImport3.ts @@ -0,0 +1,32 @@ +/// + +// @strict: true +// @noImplicitAny: true +// @noLib: true + +// @Filename: /a.ts +////export namespace things { +//// export namespace stuff { +//// export class User {} +//// } +////} +////export declare function getEmail(thing: T, user: things.stuff.User): string; + +// @Filename: /b.ts +////import { getEmail } from "./a"; +//// +////export function f([|user|]) { +//// getEmail(42, user); +////} + +goTo.file("/b.ts"); + +verify.codeFix({ + description: "Infer parameter types from usage", + newFileContent: +`import { getEmail, things } from "./a"; + +export function f(user: things.stuff.User) { + getEmail(42, user); +}` +}); diff --git a/tests/cases/fourslash/completionNoAutoInsertQuestionDotWithUserPreferencesOff.ts b/tests/cases/fourslash/completionNoAutoInsertQuestionDotWithUserPreferencesOff.ts new file mode 100644 index 00000000000..a1071a37f93 --- /dev/null +++ b/tests/cases/fourslash/completionNoAutoInsertQuestionDotWithUserPreferencesOff.ts @@ -0,0 +1,20 @@ +/// +// @strict: true + +//// interface User { +//// address?: { +//// city: string; +//// "postal code": string; +//// } +//// }; +//// declare const user: User; +//// user.address[|./**/|] + +verify.completions({ + marker: "", + exact: [], + preferences: { + includeInsertTextCompletions: true, + includeAutomaticOptionalChainCompletions: false + }, +}); diff --git a/tests/cases/fourslash/completionsGenericUnconstrained.ts b/tests/cases/fourslash/completionsGenericUnconstrained.ts new file mode 100644 index 00000000000..3865dc51561 --- /dev/null +++ b/tests/cases/fourslash/completionsGenericUnconstrained.ts @@ -0,0 +1,14 @@ +/// +// @strict: true + +////function f(x: T) { +//// return x; +////} +//// +////f({ /**/ }); + + +verify.completions({ + marker: "", + exact: [] +}); diff --git a/tests/cases/fourslash/completionsRedeclareModuleAsGlobal.ts b/tests/cases/fourslash/completionsRedeclareModuleAsGlobal.ts new file mode 100644 index 00000000000..3dd528cde17 --- /dev/null +++ b/tests/cases/fourslash/completionsRedeclareModuleAsGlobal.ts @@ -0,0 +1,35 @@ +/// + +// 32675 - if this fails there are two copies of assert in completions + +// @esModuleInterop: true, +// @target: esnext + +// @Filename: /myAssert.d.ts +////declare function assert(value:any, message?:string):void; +////export = assert; +////export as namespace assert; + +// @Filename: /ambient.d.ts +////import assert from './myAssert'; +//// +////type Assert = typeof assert; +//// +////declare global { +//// const assert: Assert; +////} + +// @Filename: /index.ts +/////// +////asser/**/; + +verify.completions({ + marker: "", + includes: [ + { + name: "assert", + sortText: completion.SortText.GlobalsOrKeywords + } + ], + preferences: { includeCompletionsForModuleExports: true, includeInsertTextCompletions: true } +}); diff --git a/tests/cases/fourslash/completionsWithGenericStringLiteral.ts b/tests/cases/fourslash/completionsWithGenericStringLiteral.ts new file mode 100644 index 00000000000..6547dee7cd3 --- /dev/null +++ b/tests/cases/fourslash/completionsWithGenericStringLiteral.ts @@ -0,0 +1,11 @@ +/// +// @strict: true + +//// declare function get(obj: T, key: K): T[K]; +//// get({ hello: 123, world: 456 }, "/**/"); + +verify.completions({ + marker: "", + includes: ['hello', 'world'] +}); + diff --git a/tests/cases/fourslash/completionsWithOptionalPropertiesGeneric.ts b/tests/cases/fourslash/completionsWithOptionalPropertiesGeneric.ts new file mode 100644 index 00000000000..7bd9d566b84 --- /dev/null +++ b/tests/cases/fourslash/completionsWithOptionalPropertiesGeneric.ts @@ -0,0 +1,19 @@ +/// +// @strict: true + +//// interface MyOptions { +//// hello?: boolean; +//// world?: boolean; +//// } +//// declare function bar(options?: Partial): void; +//// bar({ hello, /*1*/ }); + +verify.completions({ + marker: '1', + includes: [ + { + sortText: completion.SortText.OptionalMember, + name: 'world' + }, + ] +}) diff --git a/tests/cases/fourslash/completionsWithOptionalPropertiesGenericConstructor.ts b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericConstructor.ts new file mode 100644 index 00000000000..6959ae11781 --- /dev/null +++ b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericConstructor.ts @@ -0,0 +1,27 @@ +/// +// @strict: true + +//// interface Options { +//// someFunction?: () => string +//// anotherFunction?: () => string +//// } +//// +//// export class Clazz { +//// constructor(public a: T) {} +//// } +//// +//// new Clazz({ /*1*/ }) + +verify.completions({ + marker: '1', + includes: [ + { + sortText: completion.SortText.OptionalMember, + name: 'someFunction' + }, + { + sortText: completion.SortText.OptionalMember, + name: 'anotherFunction' + }, + ] +}) diff --git a/tests/cases/fourslash/completionsWithOptionalPropertiesGenericDeep.ts b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericDeep.ts new file mode 100644 index 00000000000..b1ecfc29e7e --- /dev/null +++ b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericDeep.ts @@ -0,0 +1,23 @@ +/// +// @strict: true + +//// interface DeepOptions { +//// another?: boolean; +//// } +//// interface MyOptions { +//// hello?: boolean; +//// world?: boolean; +//// deep?: DeepOptions +//// } +//// declare function bar(options?: Partial): void; +//// bar({ deep: {/*1*/} }); + +verify.completions({ + marker: '1', + includes: [ + { + sortText: completion.SortText.OptionalMember, + name: 'another' + }, + ] +}) diff --git a/tests/cases/fourslash/completionsWithOptionalPropertiesGenericPartial.ts b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericPartial.ts new file mode 100644 index 00000000000..291d342f359 --- /dev/null +++ b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericPartial.ts @@ -0,0 +1,33 @@ +/// +// @strict: true + +//// interface Foo { +//// a_a: boolean; +//// a_b: boolean; +//// a_c: boolean; +//// b_a: boolean; +//// } +//// function partialFoo>(t: T) {return t} +//// partialFoo({ /*1*/ }); + +verify.completions({ + marker: '1', + includes: [ + { + sortText: completion.SortText.OptionalMember, + name: 'a_a' + }, + { + sortText: completion.SortText.OptionalMember, + name: 'a_b' + }, + { + sortText: completion.SortText.OptionalMember, + name: 'a_c' + }, + { + sortText: completion.SortText.OptionalMember, + name: 'b_a' + }, + ] +}) diff --git a/tests/cases/fourslash/completionsWithOptionalPropertiesGenericPartial2.ts b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericPartial2.ts new file mode 100644 index 00000000000..e52d36c6816 --- /dev/null +++ b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericPartial2.ts @@ -0,0 +1,22 @@ +/// +// @strict: true + +//// interface Foo { +//// a: boolean; +//// } +//// function partialFoo>(x: T, y: T) {return t} +//// partialFoo({ a: true, b: true }, { /*1*/ }); + +verify.completions({ + marker: '1', + includes: [ + { + sortText: completion.SortText.OptionalMember, + name: 'a' + }, + { + sortText: completion.SortText.OptionalMember, + name: 'b' + } + ] +}) diff --git a/tests/cases/fourslash/completionsWithOptionalPropertiesGenericPartial3.ts b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericPartial3.ts new file mode 100644 index 00000000000..44d2118365f --- /dev/null +++ b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericPartial3.ts @@ -0,0 +1,29 @@ +/// +// @strict: true + +////interface Foo { +//// a: boolean; +////} +////function partialFoo>(x: T, y: T extends { b?: boolean } ? T & { c: true } : T) { +//// return x; +////} +//// +////partialFoo({ a: true, b: true }, { /*1*/ }); + + +verify.completions({ + marker: '1', + includes: [ + { + sortText: completion.SortText.OptionalMember, + name: 'a' + }, + { + sortText: completion.SortText.OptionalMember, + name: 'b' + }, + { + name: 'c' + } + ] +}) diff --git a/tests/cases/fourslash/completionsWithOptionalPropertiesGenericValidBoolean.ts b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericValidBoolean.ts new file mode 100644 index 00000000000..ebba38f0dd3 --- /dev/null +++ b/tests/cases/fourslash/completionsWithOptionalPropertiesGenericValidBoolean.ts @@ -0,0 +1,19 @@ +/// +// @strict: true + +//// interface MyOptions { +//// hello?: boolean; +//// world?: boolean; +//// } +//// declare function bar(options?: Partial): void; +//// bar({ hello: true, /*1*/ }); + +verify.completions({ + marker: '1', + includes: [ + { + sortText: completion.SortText.OptionalMember, + name: 'world' + }, + ] +}) diff --git a/tests/cases/fourslash/documentHighlightsInvalidGlobalThis.ts b/tests/cases/fourslash/documentHighlightsInvalidGlobalThis.ts new file mode 100644 index 00000000000..b9c8008e132 --- /dev/null +++ b/tests/cases/fourslash/documentHighlightsInvalidGlobalThis.ts @@ -0,0 +1,9 @@ +/// + +////declare global { +//// export { globalThis as [|global|] } +////} + +for (const r of test.ranges()) { + verify.documentHighlightsOf(r, [r]); +} diff --git a/tests/cases/fourslash/formattingSpaceBetweenOptionalChaining.ts b/tests/cases/fourslash/formattingSpaceBetweenOptionalChaining.ts new file mode 100644 index 00000000000..53f2debf559 --- /dev/null +++ b/tests/cases/fourslash/formattingSpaceBetweenOptionalChaining.ts @@ -0,0 +1,10 @@ +/// + +/////*1*/a ?. b ?. c . d; +/////*2*/o . m() ?. length; + +format.document(); +goTo.marker("1"); +verify.currentLineContentIs("a?.b?.c.d;"); +goTo.marker("2"); +verify.currentLineContentIs("o.m()?.length;"); diff --git a/tests/cases/fourslash/fourslash.ts b/tests/cases/fourslash/fourslash.ts index 5672f430434..cd184df3bed 100644 --- a/tests/cases/fourslash/fourslash.ts +++ b/tests/cases/fourslash/fourslash.ts @@ -583,6 +583,7 @@ declare namespace FourSlashInterface { readonly quotePreference?: "double" | "single"; readonly includeCompletionsForModuleExports?: boolean; readonly includeInsertTextCompletions?: boolean; + readonly includeAutomaticOptionalChainCompletions?: boolean; readonly importModuleSpecifierPreference?: "relative" | "non-relative"; readonly importModuleSpecifierEnding?: "minimal" | "index" | "js"; } diff --git a/tests/cases/fourslash/importFixesGlobalTypingsCache.ts b/tests/cases/fourslash/importFixesGlobalTypingsCache.ts new file mode 100644 index 00000000000..21c8ddf0ebe --- /dev/null +++ b/tests/cases/fourslash/importFixesGlobalTypingsCache.ts @@ -0,0 +1,18 @@ +/// + +// @Filename: /project/tsconfig.json +//// { "compilerOptions": { "allowJs": true, "checkJs": true } } + +// @Filename: /Library/Caches/typescript/node_modules/@types/react-router-dom/package.json +//// { "name": "react-router-dom" } + +// @Filename: /Library/Caches/typescript/node_modules/@types/react-router-dom/index.d.ts +////export class BrowserRouter {} + +// @Filename: /project/index.js +////BrowserRouter/**/ + +goTo.file("/project/index.js"); +verify.importFixAtPosition([`import { BrowserRouter } from "react-router-dom"; + +BrowserRouter`]); diff --git a/tests/cases/fourslash/quickInfoInheritedJSDoc.ts b/tests/cases/fourslash/quickInfoInheritedJSDoc.ts new file mode 100644 index 00000000000..7b1f54815b7 --- /dev/null +++ b/tests/cases/fourslash/quickInfoInheritedJSDoc.ts @@ -0,0 +1,14 @@ +/// +// #32708 + +////interface I { +//// /** only once please */ +//// t: T +////} +////interface C extends I { +//// t: T +////} +////declare var cnsb: C & C & C; +////cnsb.t/**/ + +verify.quickInfoAt("", "(property) C.t: never", "only once please"); diff --git a/tests/cases/fourslash/quickInfoMappedTypeMethods.ts b/tests/cases/fourslash/quickInfoMappedTypeMethods.ts new file mode 100644 index 00000000000..8107775b9e4 --- /dev/null +++ b/tests/cases/fourslash/quickInfoMappedTypeMethods.ts @@ -0,0 +1,9 @@ +/// +// https://github.com/microsoft/TypeScript/issues/32983 + +////type M = { [K in 'one']: any }; +////const x: M = { +//// /**/one() {} +////} + +verify.quickInfoAt("", "(property) one: any"); diff --git a/tests/cases/fourslash/syntacticClassificationsMergeConflictMarker1.ts b/tests/cases/fourslash/syntacticClassificationsMergeConflictMarker1.ts new file mode 100644 index 00000000000..b78a6f35982 --- /dev/null +++ b/tests/cases/fourslash/syntacticClassificationsMergeConflictMarker1.ts @@ -0,0 +1,16 @@ +/// + +//// <<<<<<< HEAD +//// "AAAA" +//// ======= +//// "BBBB" +//// >>>>>>> Feature + + +var c = classification; +verify.syntacticClassificationsAre( + c.comment("<<<<<<< HEAD"), + c.stringLiteral("\"AAAA\""), + c.comment("======="), + c.stringLiteral("\"BBBB\""), + c.comment(">>>>>>> Feature")); \ No newline at end of file